我是hibernate的新手,尝试学习一对多的关系,代码正在执行而没有任何错误,但它只创建不插入值的表。我想在Employee和他分配的任务之间建立一对多的关系。一名员工可以完成多项任务。
Employee.java
@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany
private Set<Task> taklist = new HashSet<Task>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Task> getTaklist() {
return taklist;
}
public void setTaklist(Set<Task> taklist) {
this.taklist = taklist;
}
}
Task.java
@Entity
public class Task {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int taskid;
private String taskname;
public int getTaskid() {
return taskid;
}
public void setTaskid(int taskid) {
this.taskid = taskid;
}
public String getTaskname() {
return taskname;
}
public void setTaskname(String taskname) {
this.taskname = taskname;
}
}
hibernate.cfg.xml中
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernate
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<property name="connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="com.sumeet.onetomany.Employee"></mapping>
<mapping class="com.sumeet.onetomany.Task"></mapping>
</session-factory>
</hibernate-configuration>
App.java
package com.sumeet.onetomany;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class App {
public static void main(String args[]){
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Employee emp = new Employee();
emp.setName("Arun");
Task task = new Task();
task.setTaskname("Office Work");
Task task2 = new Task();
task2.setTaskname("Home Work");
emp.getTaklist().add(task);
session.beginTransaction();
session.save(emp);
session.close();
}
}
答案 0 :(得分:1)
您需要提交交易
Transaction tx = session.beginTransaction();
session.save(emp);
tx.commit(); // Need to commit transaction
session.close();