Hibernate-Usage(basis)(hibernate基本用法)
来源:互联网 发布:python定义json字符串 编辑:程序博客网 时间:2024/04/30 06:27
hibernate基本用法
part_0:下载源码(http://download.csdn.net/detail/love_legain/9744626)
part_1:导入基础所需包(这些包都是必须的,其中log4j用户记录日志)
antlr-2.7.7.jarcdi-api-1.1.jarclassmate-1.3.0.jardom4j-1.6.1.jarel-api-2.2.jargeronimo-jta_1.1_spec-1.1.1.jarhibernate-commons-annotations-5.0.1.Final.jarhibernate-core-5.2.5.Final.jarhibernate-jpa-2.1-api-1.0.0.Final.jarhibernate-jpamodelgen-5.2.5.Final.jarjandex-2.0.3.Final.jarjavassist-3.20.0-GA.jarjavax.inject-1.jarjboss-interceptors-api_1.1_spec-1.0.0.Beta1.jarjboss-logging-3.3.0.Final.jarjsr250-api-1.0.jarlog4j-1.2.17.jarmysql-connector-java-5.1.7-bin.jarslf4j-api-1.7.7.jarslf4j-log4j12-1.7.5.jar
part_2:实体类(User)
package cn.mike.entity;public class User { private int uid; private String username; private String password; public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
part_3:User的映射配置文件(User.hbm.xml)
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="cn.mike.entity.User" table="t_user"> <id name="uid" column="uid"> <generator class="native" /> </id> <property name="username" column="username" /> <property name="password" column="password" /> </class></hibernate-mapping>
part_4:Company.java
package cn.mike.entity;import java.util.Set;/** * @author Administrator * @usage 用于一对多关系的练习(一个公司对应多个雇员) */public class Company { private Integer comId; private String comName; private String comHeadquarters; private Set<Employee> employees; public Company(Integer comId, String comName, String comHeadquarters, Set<Employee> employees) { // 在此之前,必须保证要有无参的构造方法存在 this.comId = comId; this.comName = comName; this.comHeadquarters = comHeadquarters; this.employees = employees; } public Company() {// 必须保证要有无参的构造方法 } public Integer getComId() { return comId; } public void setComId(Integer comId) { this.comId = comId; } public String getComName() { return comName; } public void setComName(String comName) { this.comName = comName; } public String getComHeadquarters() { return comHeadquarters; } public void setComHeadquarters(String comHeadquarters) { this.comHeadquarters = comHeadquarters; } public Set<Employee> getEmployees() { return employees; } public void setEmployees(Set<Employee> employees) { this.employees = employees; }}
part_5:Company.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="cn.mike.entity.Company" table="t_company"> <id name="comId" column="comId"> <generator class="native" /> </id> <property name="comName" column="comName" /> <property name="comHeadquarters" column="comHeadquarters" /> <set name="employees" cascade="save-update,delete" inverse="true"> <key column="comEmpId" /> <one-to-many class="cn.mike.entity.Employee" /> </set> </class></hibernate-mapping>
part_6:Employee.java
package cn.mike.entity;/** * @author Administrator * @usage 用于一对多关系的练习(一个公司对应多个雇员) */public class Employee { private Integer empId; private String empName; private String empGender; private Company company; public Employee() {// 必须保证要有无参的构造方法 } public Employee(Integer empId, String empName, String empGender, Company company) { // 在此之前,必须保证要有无参的构造方法存在 this.empId = empId; this.empName = empName; this.empGender = empGender; this.company = company; } public Integer getEmpId() { return empId; } public void setEmpId(Integer empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getEmpGender() { return empGender; } public void setEmpGender(String empGender) { this.empGender = empGender; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; }}
part_7:Employee.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="cn.mike.entity.Employee" table="t_emptact"> <id name="empId" column="empId"> <generator class="native" /> </id> <property name="empName" column="empName" /> <property name="empGender" column="empGender" /> <many-to-one name="company" class="cn.mike.entity.Company" column="comEmpId"></many-to-one> </class></hibernate-mapping>
part_8:Course.java
package cn.mike.entity;import java.util.Set;/** * @author Administrator * @usage Course:课程类,用于多对对练习的类(一门课程可以被多个学生选修) */public class Course { private Integer courseID; private String courseName; private Set<Student> students;// 选修该课程的学生 public Course() { } public Course(Integer courseID, String courseName, Set<Student> students) { this.courseID = courseID; this.courseName = courseName; this.students = students; } public Integer getCourseID() { return courseID; } public void setCourseID(Integer courseID) { this.courseID = courseID; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; }}
part_9:Course.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="cn.mike.entity.Course" table="COURSE"> <id name="courseID" column="courseID"> <generator class="native" /> </id> <property name="courseName" column="courseName" /> <set name="students" table="COURSE_STUDENT" cascade="save-update,delete"> <!-- 在第三张表中的键名称 --> <key column="courseID" /> <many-to-many class="cn.mike.entity.Student" column="stuID" /> </set> </class></hibernate-mapping>
part_10:Student.java
package cn.mike.entity;import java.util.Set;/** * @author Administrator * @usage Student:学生类,用于多对对练习的类(一个学生可以选修多门课程) */public class Student { private Integer stuID; private String stuName; private Set<Course> courses;// 该学生选修的课程 public Student() { } public Student(Integer stuID, String stuName, Set<Course> courses) { this.stuID = stuID; this.stuName = stuName; this.courses = courses; } public Integer getStuID() { return stuID; } public void setStuID(Integer stuID) { this.stuID = stuID; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public Set<Course> getCourses() { return courses; } public void setCourses(Set<Course> courses) { this.courses = courses; }}
part_11:Student.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="cn.mike.entity.Student" table="STUDENT"> <id name="stuID" column="stuID"> <generator class="native" /> </id> <property name="stuName" column="stuName" /> <set name="courses" table="COURSE_STUDENT"> <!-- 在第三张表中的键名称 --> <key column="stuID" /> <many-to-many class="cn.mike.entity.Course" column="courseID" /> </set> </class></hibernate-mapping>
part_12:log4j.properties
log4j.rootLogger=debug, stdout, Rlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.errlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%nlog4j.appender.R=org.apache.log4j.RollingFileAppenderlog4j.appender.R.File=log4j.loglog4j.appender.R.MaxFileSize=100KBlog4j.appender.R.MaxBackupIndex=1log4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%p %t %c - %m%nlog4j.logger.com.foo=WARN
part_13: HibernateUtils.java
package cn.mike.utils;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtils { private static final Configuration cfg; private static final SessionFactory sessFac; static { cfg = new Configuration().configure(); sessFac = cfg.buildSessionFactory(); } public static SessionFactory getSessionFactory() { return sessFac; } public static Session getBoundSession() { return sessFac.getCurrentSession(); } public static void closeSessionFactory() { sessFac.close(); } public static void main(String[] args) { // System.out.println("demo's running..."); }}
part_14:hibernate核心配置文件(hibernate.cfg.xml)
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <!-- 1.配置数据库信息 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///hibernate</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">3713</property> <!-- 2.配置hibernate信息 --> <!-- print all generated SQL to the console --> <property name="hibernate.show_sql">true</property> <!-- format SQL in log and console --> <property name="hibernate.format_sql">true</property> <!-- update:若表不存在就新建,否则就更新 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- hibernate.dialect --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 与本地线程绑定session --> <property name="hibernate.current_session_context_class">thread</property> <!-- 3.将映射文件放到核心配置文件中 --> <mapping resource="cn/mike/entity/User.hbm.xml" /> <mapping resource="cn/mike/entity/Company.hbm.xml" /> <mapping resource="cn/mike/entity/Employee.hbm.xml" /> <mapping resource="cn/mike/entity/Course.hbm.xml" /> <mapping resource="cn/mike/entity/Student.hbm.xml" /> </session-factory></hibernate-configuration>
part_15:QualityTest.java(单元测试)
package cn.mike.demo;import java.util.HashSet;import java.util.List;import java.util.Set;import org.hibernate.Criteria;import org.hibernate.SQLQuery;import org.hibernate.Session;import org.hibernate.Transaction;import org.hibernate.query.Query;import org.junit.Test;import cn.mike.entity.Employee;import cn.mike.entity.Student;import cn.mike.entity.Company;import cn.mike.entity.Course;import cn.mike.entity.User;import cn.mike.utils.HibernateUtils;public class QualityTest { @Test public void testFunction() { // 单表操作(user) // testAdd(); // testUpdate(); // testGet(); // testDelete(); // testSaveOrUpdate(); // testBoundSession(); // testQuery(); // testCriteria(); // testSQLQuery(); // 多表操作(一对多关系,一个公司对应多个雇员) // testCascadeSave_1();// (复杂写法) // testCascadeSave_2();// 简化写法 // testCascadeDelete();// 级联删除 // testCascadeUpdate();// 修改 // 多表(多对多关系,多门课程对应对个学生) // testM2MSave();// test many-to-many save // testM2MDelete();// test many-to-many delete(一般不使用这种方法) // testM2MAdd();// test many-to-many add // testM2MRemove();// test many-to-many remove } private void testM2MRemove() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // e.g.让Michelle不再选修DataStructure Course course = sess.get(Course.class, 1); Student student = sess.get(Student.class, 3); course.getStudents().remove(student); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } private void testM2MAdd() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // e.g.让Michelle选修DataStructure Course course = sess.get(Course.class, 1); Student student = sess.get(Student.class, 3); course.getStudents().add(student); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } private void testM2MDelete() {// 先要配置cascade="save-update,delete" Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // 删除所有选修DataStructure的学生 sess.delete(sess.get(Course.class, 4)); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } /** * 多对多的级联保存操作(需要配置在主动提交的类中.e.g.save(course)那就配置在course的xml文件中) * */ private void testM2MSave() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // 两门课程(数据结构<DataStructure>和算法<Algorithm>) Course courseDS = new Course(null, "DataStructure", null); Course courseAlg = new Course(null, "Algorithm", null); // 三个学生(Mike,Michael,Michelle) Student stuMike = new Student(null, "Mike", null); Student stuMichael = new Student(null, "Micheal", null); Student stuMichelle = new Student(null, "Michelle", null); // dsStudents:选修DataStructure的学生,algStudent:选修Algtithm的学生 Set<Student> dsStudents = (null == courseDS.getStudents() ? new HashSet<Student>() : courseDS.getStudents()); Set<Student> algStudents = (null == courseAlg.getStudents() ? new HashSet<Student>() : courseAlg.getStudents()); dsStudents.add(stuMike);// Mike选修了DataStructure dsStudents.add(stuMichael);// Michael选修了DataStructure algStudents.add(stuMichael);// Michael选修了Algrithm algStudents.add(stuMichelle);// Michelle选修了Algrithm courseDS.setStudents(dsStudents); courseAlg.setStudents(algStudents); sess.save(courseDS); sess.save(courseAlg); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } /** * 因为hibernate的有双向维护外键的机制,所以会导致两次修改,在主表中设置属性inverse="true"(主表:一对多中的"一") * <set name="employees" cascade="save-update,delete" inverse="true"> */ private void testCascadeUpdate() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // 级联修改,将6号员工bdemp_1设为ali的员工 Company comAli = sess.get(Company.class, 3); Employee emp = sess.get(Employee.class, 6); comAli.getEmployees().add(emp); emp.setCompany(comAli); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } /** * 如要级联删除,还需添加配置:<set name="contacts" cascade="save-update,delete"> */ private void testCascadeDelete() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // 级联删除一个公司(customer)和两个员工(contact) sess.delete(sess.get(Company.class, 2)); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } /** * 级联保存的简化写法(在此之前需要配置映射文件cascade="save-update") */ private void testCascadeSave_2() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // 级联添加一个公司(customer)和两个员工(contact) Company compAli = new Company(null, "Alibaba", "Hangzhou", new HashSet<Employee>()); Employee emp_1 = new Employee(null, "Aliemp_1", "female", null); Employee emp_2 = new Employee(null, "Aliemp_2", "male", null); // 把员工对象 放到公司对象的set集合里面 compAli.getEmployees().add(emp_1); compAli.getEmployees().add(emp_2); sess.save(compAli);// 仅需要保存公司即可 tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } /** * 级联操作的演示(复杂写法) */ private void testCascadeSave_1() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); // 级联添加一个公司(customer)和两个员工(contact) Company comBd = new Company(null, "baidu", "Beijing", null); Employee emp_1 = new Employee(null, "bdemp_1", "female", null); Employee emp_2 = new Employee(null, "bdemp_2", "male", null); Set<Employee> bdemps = new HashSet<Employee>(); bdemps.add(emp_1); bdemps.add(emp_2); // 把员工对象 放到公司对象的set集合里面 comBd.setEmployees(bdemps); // 把公司对象放到员工里面 emp_1.setCompany(comBd); emp_1.setCompany(comBd); sess.save(comBd); sess.save(emp_1); sess.save(emp_2); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory();// 实际开发中不需要关闭 } } private void testSQLQuery() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); SQLQuery sqlQuery = sess.createSQLQuery("SELECT * FROM t_user"); // System.out.println("way 1 : "); // List<Object[]> userList = sqlQuery.list(); // for (Object[] aList : userList) { // System.out.println(Arrays.toString(aList)); // } // System.out.println("way 2 : "); sqlQuery.addEntity(User.class); List<User> userList_2 = sqlQuery.list(); for (User user : userList_2) { System.out.println(user.getUsername() + " : " + user.getPassword()); } tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory(); } } private void testCriteria() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); Criteria criteria = sess.createCriteria(User.class); List<User> userList = criteria.list(); for (User user : userList) { System.out.println(user.getUsername() + " : " + user.getPassword()); } tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory(); } } private void testQuery() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); Query query = sess.createQuery("from User"); List<User> userList = query.list(); for (User user : userList) { System.out.println(user.getUsername() + " : " + user.getPassword()); } tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; HibernateUtils.closeSessionFactory(); } } private void testBoundSession() { Session sess = null; Transaction tx = null; try { sess = HibernateUtils.getBoundSession(); tx = sess.beginTransaction(); User user = new User(); user.setUsername("李san"); sess.saveOrUpdate(user); tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { // sess.close();//与本地线程绑定后就不需要close了; } } private void testSaveOrUpdate() { Session sess = HibernateUtils.getSessionFactory().openSession(); Transaction tx = sess.beginTransaction(); // User user = sess.get(User.class, 3); // User user = new User(); // user.setUid(3); // user.setUsername("张"); // sess.save(user); User user = new User(); user.setUid(3); user.setUsername("李"); sess.saveOrUpdate(user); tx.commit(); sess.close(); } private void testDelete() { Session sess = HibernateUtils.getSessionFactory().openSession(); Transaction tx = sess.beginTransaction(); // way 1: // User user = sess.get(User.class, 1); // sess.delete(user); // way 2: User user_2 = new User(); user_2.setUid(2); sess.delete(user_2); tx.commit(); sess.close(); } private void testUpdate() { Session sess = HibernateUtils.getSessionFactory().openSession(); Transaction tx = sess.beginTransaction(); User user = sess.get(User.class, 1); user.setUsername("sunguoqing"); sess.update(user); tx.commit(); sess.close(); } private void testGet() { Session sess = HibernateUtils.getSessionFactory().openSession(); Transaction tx = sess.beginTransaction(); User user = sess.get(User.class, 1); System.out.println(user.getUsername() + " : " + user.getPassword()); tx.commit(); sess.close(); } private void testAdd() { Session sess = HibernateUtils.getSessionFactory().openSession(); Transaction tx = sess.beginTransaction(); User user = new User(); user.setUsername("孙国庆4"); user.setPassword("254"); sess.save(user); tx.commit(); sess.close(); // HibernateUtils.closeSessionFactory(); }}
part_16:视图
part_17:下载源码(http://download.csdn.net/detail/love_legain/9744626)
0 0
- Hibernate-Usage(basis)(hibernate基本用法)
- Hibernate Criteria 基本用法
- Hibernate基本用法:体系结构
- hibernate-基本用法1
- hibernate-基本用法2
- 【Hibernate】(1)Hibernate的基本用法
- hibernate inverse 的基本用法
- Hibernate的一些基本用法
- Hibernate基本用法:Configuration对象
- 第5章 Hibernate的基本用法 5.2 Hibernate入门
- Hibernate------hibernate基本映射
- Hibernate中的Query一些基本用法
- Hibernate中的Query一些基本用法
- Hibernate中的Query一些基本用法
- Hibernate中的Query一些基本用法
- Hibernate中的Query一些基本用法
- Hibernate的基本API的用法
- Hibernate之HQL的基本用法
- 1.23 第一次题解
- ZCMU-1677-小学生小明,圣光会制裁你!!!
- 反思
- 使用nodejs数据库ORM(Object Relational Mapping)模块
- Linux 使用mysql简单教程
- Hibernate-Usage(basis)(hibernate基本用法)
- Python爬虫/文本处理/科学计算/机器学习——工具包总结
- 南邮离散数学实验三-偏序关系中盖住关系的求取及格论中有补格的判定
- 2016 总结记
- 关于mysql中由于类型转换导致索引无法使用的问题
- LeetCode 231. Power of Two
- CodeForces 59AWord 水题
- Spring自动检测并装配bean
- 远程调用的几种方式