2019独角兽企业重金招聘Python工程师标准>>>
开发环境:Mysql+Eclipse
一对多单向的列子原理:一个班级,多个学生,学生端为多的一端,他们拥有一个外键指向相同的班级。
项目结构
需要的jar包
hibernate.cfg.xml
<!-- 配置mysql数据库的连接参数 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 驱动程序名 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 自动创建表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 控制台打印sql语句 -->
<property name="show_sql">true</property>
<!-- 数据库名 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<!-- 用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 密码 -->
<property name="hibernate.connection.password"></property>
<!-- 对应的实体 -->
<mapping class="cn.dao.Classes"/>
<mapping class="cn.dao.Student"/>
</session-factory>
实体类:
- Classes.java
package cn.dao;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "classes")
public class Classes implements Serializable {
private Long id;
private String name;
private String desc;
private Set<Student> students = new HashSet<Student>();
@Id
@Column(name = "cid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "cname")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "cdesc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
@JoinColumn(name = "cid")
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
//测试打印
@Override
public String toString() {
return "Classes [id=" + id + ", name=" + name + ", desc=" + desc + ", students=" + students + "]";
}
}
2.Student.java
package cn.dao;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student implements Serializable {
private Long id;
private String name;
private String sex;
@Id
@Column(name = "sid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "sname")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "sex")
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
创建一个打开session的工具类:HibernateUtil
package cn.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static Session session;
static {
// 读取Hibernate的配置文件,进行初始化的操作
Configuration config = new Configuration().configure();
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
StandardServiceRegistry registry = ssrb.build();
sessionFactory = config.buildSessionFactory(registry);
}
/**
* 获取SessionFactory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 获取session
*/
public static Session getSession() {
return sessionFactory.openSession();
}
/**
* 关闭session
*/
public static void closeSession() {
if (session != null) {
session.close();
}
}
}
最后一个测试,实现简单的增删改查功能:OneToMany.java
package cn.test;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.dao.Classes;
import cn.dao.Student;
import cn.utils.HibernateUtil;
/**
* 单向的一对多关联操作
*
* @author hasee
*
*/
public class OneToMany {
public static void main(String[] args) {
query();
}
public static void save() {
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
Classes classes = new Classes();
classes.setName("ClassOne");
classes.setDesc("This is ClassOne");
Set<Student> students = new HashSet<Student>();
Student student = new Student();
student.setName("Mike");
student.setSex("boy");
students.add(student);
classes.setStudents(students);
session.save(classes);
transaction.commit();
HibernateUtil.closeSession();
}
public static void edit(){
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
Classes classes = (Classes) session.get(Classes.class, 1L);
Set<Student> students = classes.getStudents();
for (Student student : students) {
student.setName("Jary");
}
transaction.commit();
HibernateUtil.closeSession();
}
public static void delete(){
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
Classes classes = (Classes) session.get(Classes.class, 1L);
session.delete(classes);
transaction.commit();
HibernateUtil.closeSession();
}
public static void query(){
Session session = HibernateUtil.getSession();
Query query = session.createQuery("from Classes");
List<Classes> list = query.list();
for (Classes classes : list) {
System.out.println(classes.toString());
}
}
}