当前位置:   article > 正文

Java Hibernate 之 CRUD 操作_java hibenate crud

java hibenate crud

CRUD是指在做计算处理时的增加(Create)、读取(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写.

下面列举实例来讲解这几个操作:

实体类

  1. package com.oumyye.model;
  2. public class Student {
  3. private long id;
  4. private String name;
  5. private Class c;
  6. public long getId() {
  7. return id;
  8. }
  9. public void setId(long id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public Class getC() {
  19. return c;
  20. }
  21. public void setC(Class c) {
  22. this.c = c;
  23. }
  24. @Override
  25. public String toString() {
  26. return "Student [id=" + id + ", name=" + name + "]";
  27. }
  28. }
  1. package com.oumyye.model;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. public class Class {
  5. private long id;
  6. private String name;
  7. private Set<Student> students=new HashSet<Student>();
  8. public long getId() {
  9. return id;
  10. }
  11. public void setId(long id) {
  12. this.id = id;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public Set<Student> getStudents() {
  21. return students;
  22. }
  23. public void setStudents(Set<Student> students) {
  24. this.students = students;
  25. }
  26. }

映射文件:
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 package="com.oumyye.model">
 <class name="Student" table="t_student">
  <id column="stuId" name="id">
   <generator class="native"/>
  </id>
  <property column="stuName" generated="never" lazy="false" name="name"/>
  <many-to-one cascade="save-update" class="com.oumyye.model.Class"
   column="classId" name="c"/>
 </class>
</hibernate-mapping>

Class.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 package="com.oumyye.model">
 <class name="Class" table="t_class">
  <id column="classId" name="id">
   <generator class="native"/>
  </id>
  <property column="className" generated="never" lazy="false" name="name"/>
  <set cascade="delete" inverse="true" name="students" sort="unsorted">
   <key column="classId"/>
   <one-to-many class="com.oumyye.model.Student"/>
  </set>
 </class>
</hibernate-mapping>

工具类:可以有myeclipse生成

  1. package com.oumyye.util;
  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Session;
  4. import org.hibernate.cfg.Configuration;
  5. import org.hibernate.cfg.AnnotationConfiguration;
  6. /**
  7. * Configures and provides access to Hibernate sessions, tied to the
  8. * current thread of execution. Follows the Thread Local Session
  9. * pattern, see {@link http://hibernate.org/42.html }.
  10. */
  11. public class HibernateSessionFactory {
  12. /**
  13. * Location of hibernate.cfg.xml file.
  14. * Location should be on the classpath as Hibernate uses
  15. * #resourceAsStream style lookup for its configuration file.
  16. * The default classpath location of the hibernate config file is
  17. * in the default package. Use #setConfigFile() to update
  18. * the location of the configuration file for the current session.
  19. */
  20. private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
  21. private static org.hibernate.SessionFactory sessionFactory;
  22. private static Configuration configuration = new AnnotationConfiguration(); private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
  23. private static String configFile = CONFIG_FILE_LOCATION;
  24. static {
  25. try {
  26. configuration.configure(configFile);
  27. sessionFactory = configuration.buildSessionFactory();
  28. } catch (Exception e) {
  29. System.err.println("%%%% Error Creating SessionFactory %%%%");
  30. e.printStackTrace();
  31. }
  32. }
  33. private HibernateSessionFactory() {
  34. }
  35. /**
  36. * Returns the ThreadLocal Session instance. Lazy initialize
  37. * the <code>SessionFactory</code> if needed.
  38. *
  39. * @return Session
  40. * @throws HibernateException
  41. */
  42. public static Session getSession() throws HibernateException {
  43. Session session = (Session) threadLocal.get();
  44. if (session == null || !session.isOpen()) {
  45. if (sessionFactory == null) {
  46. rebuildSessionFactory();
  47. }
  48. session = (sessionFactory != null) ? sessionFactory.openSession()
  49. : null;
  50. threadLocal.set(session);
  51. }
  52. return session;
  53. }
  54. /**
  55. * Rebuild hibernate session factory
  56. *
  57. */
  58. public static void rebuildSessionFactory() {
  59. try {
  60. configuration.configure(configFile);
  61. sessionFactory = configuration.buildSessionFactory();
  62. } catch (Exception e) {
  63. System.err.println("%%%% Error Creating SessionFactory %%%%");
  64. e.printStackTrace();
  65. }
  66. }
  67. /**
  68. * Close the single hibernate session instance.
  69. *
  70. * @throws HibernateException
  71. */
  72. public static void closeSession() throws HibernateException {
  73. Session session = (Session) threadLocal.get();
  74. threadLocal.set(null);
  75. if (session != null) {
  76. session.close();
  77. }
  78. }
  79. /**
  80. * return session factory
  81. *
  82. */
  83. public static org.hibernate.SessionFactory getSessionFactory() {
  84. return sessionFactory;
  85. }
  86. /**
  87. * return session factory
  88. *
  89. * session factory will be rebuilded in the next call
  90. */
  91. public static void setConfigFile(String configFile) {
  92. HibernateSessionFactory.configFile = configFile;
  93. sessionFactory = null;
  94. }
  95. /**
  96. * return hibernate configuration
  97. *
  98. */
  99. public static Configuration getConfiguration() {
  100. return configuration;
  101. }
  102. }

配置文件hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!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>

    <!--数据库连接设置 -->
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="connection.url">
        jdbc:mysql://localhost:3306/mytest
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- 方言 -->
    <property name="dialect">
        org.hibernate.dialect.MySQL5Dialect
    </property>

    <!-- 控制台显示SQL -->
    <property name="show_sql">true</property>

    <!-- 自动更新表结构 -->
    <property name="hbm2ddl.auto">update</property>
    <mapping resource="com/oumyye/model/Class.hbm.xml" />
    <mapping resource="com/oumyye/model/Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

测试类

package com.oumyye.service;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.oumyye.model.Class;
import com.oumyye.model.Student;
import com.oumyye.util.HibernateSessionFactory;

public class StudentTest {

    private SessionFactory sessionFactory=HibernateSessionFactory.getSessionFactory();
    private Session session;

    @Before
    public void setUp() throws Exception {
        session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务
    }

    @After
    public void tearDown() throws Exception {
         session.getTransaction().commit(); // 提交事务
         session.close(); // 关闭session
    }

    @Test
    public void testSaveClassAndStudent() {
        Class c=new Class();
        c.setName("08计本");

        Student s1=new Student();
        s1.setName("张三");
        s1.setC(c);

        Student s2=new Student();
        s2.setName("李四");
        s2.setC(c);

        session.save(s1);
        session.save(s2);

    }

    @Test
    public void testLoadClass(){
        // Class c=(Class)session.load(Class.class, Long.valueOf(2));
        Class c=(Class)session.load(Class.class, Long.valueOf(1));
        System.out.println(c.getStudents());
    }

    @Test
    public void testGetClass(){
        // Class c=(Class)session.get(Class.class, Long.valueOf(2));
        Class c=(Class)session.get(Class.class, Long.valueOf(1));
        System.out.println(c.getStudents());
    }

    @Test
    public void testUpdateClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();
        c.setName("08计算机本科2");
        session2.update(c);
        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }
    <!--更新-->
    @Test
    public void testSaveOrUpdateClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();
        c.setName("08计算机本科3");

        Class c2=new Class();
        c2.setName("09计算机本科3");
        session2.saveOrUpdate(c);
        session2.saveOrUpdate(c2);
        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }

    @Test
    public void testMergeClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();

        Class c2=(Class)session2.get(Class.class, Long.valueOf(1));
        c.setName("08计算机本科4");

        session2.merge(c);

        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }
    <!--删除-->
    @Test
    public void testDeleteStudent(){
        Student student=(Student)session.load(Student.class, Long.valueOf(1));
        session.delete(student);
    }
}

Session的入门常用方法

  • Query query = session.createQuery(hql):利用hql查询语句查询;
  • Criteria critera = session.createCriteria(Class clazz);
  • (3)Transaction tx = session.beginTransaction();     //开始事务;tx.commit()提交事务;
  • session.close();//关闭Session,此后被session管理的持久化对象变为脱管状态;
  • session.save(Object obj);    //添加
  • session.update(Object obj);     //更新
  • session.delete(Object obj);    //删除
  • Object obj = session.get(Class clazz,Serialiazble id);    //根据主键查找记录并返回;
  • Object obj = session.load(Class clazz,Serializable id);    //和get方法效果一样,但是是懒加载,即在不使用他之前他不会返回对象;
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/870901
推荐阅读
相关标签
  

闽ICP备14008679号