前面是用xml配置文档进行操作的,这一章开始使用注解来进行简单的CRUD操作。
由于是简单的操作,我们便将上一章的项目复制一份,将名称更改为Hibernate02。
1.首先是开发环境,使用Maven版本为3.5,jdk版本为9.0.1,Hibernate版本为5.0.1Final,数据库为MySQL5.7.20
2.配置Maven的pom.xml文件,由于我当前的jdk版本以及Hibernate版本所以依赖如配置文件中所列出。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cc.acme_me.hibernate</groupId> <artifactId>Hibernate02</artifactId> <version>1.0-SNAPSHOT</version> <name>Hibernate01</name> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.12.Final</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.3.4</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>5.0.1.Final</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.20.0-GA</version> </dependency> <dependency> <groupId>org.jboss</groupId> <artifactId>jandex</artifactId> <version>2.0.3.Final</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <dependency> <groupId>org.jboss.spec.javax.transaction</groupId> <artifactId>jboss-transaction-api_1.2_spec</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> </dependencies> </project>
3.Hibernate的全局配置文件hibernate.cfg.xml,同时由于使用注解,所以就不需要使用hbm.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.username">root</property> <property name="connection.password">root</property> <property name="connection.url">jdbc:mysql://localhost:3306/db_hibernate</property> <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property> <!--数据库方言--> <property name="dialect">org.hibernate.dialect.MySQL57Dialect</property> <!--显示sql语句--> <property name="show_sql">true</property> <!--格式化sql语句--> <property name="format_sql">true</property> <!--设置ddl 根据设置自动更新表结构 包括添加删除表 更新表结构--> <property name="hbm2ddl.auto">create-drop</property> <!--告诉Hibernate映射的实体类--> <mapping class="cc.acme_me.model.Student"/> </session-factory> </hibernate-configuration>
4.实体类Student,字段的注解也可以放在getter方法上。
package cc.acme_me.model; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; @Table(name = "t_student")//对应的表,name属性可选,用于定义表名,不写默认类名 @Entity//映射实体 public class Student { @Id//代表映射主键 @GenericGenerator(name = "native", strategy = "native")//定义策略然后下面使用 @GeneratedValue(generator = "native") private long id;//作为主键 @Column(name = "studentname")//@Column定义普通字段,name可选 private String name;//姓名 @Column(name = "studentage") private int age;//年龄 public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
5.工具类
package cc.acme_me.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; public class SessionUtils { public static Session openSession() { ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory(); return sessionFactory.openSession(); } }
6.最后便是测试方法。
package cc.acme_me.test; import cc.acme_me.model.Student; import cc.acme_me.utils.SessionUtils; import org.hibernate.Session; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestStudent { private Session session = null; @Before//使用该注解可以在测试方法运行前调用,我们可以使用它将获取session的方法写好,就不需要为每一个测试方法写一遍session的获取 public void openSession() { session = SessionUtils.openSession(); session.beginTransaction(); } @After//该注解是在测试方法运行后调用,我们可以在这里设置事物的提交和session的关闭 public void closeSession() { session.getTransaction().commit(); session.close(); } @Test public void testAdd() { //新建一个实体对象并设置参数 Student student = new Student(); student.setAge(18); student.setName("Admin"); //由于我们在主键策略里面使用了自增长策略,所以可以不用配置ID,Hibernate可以为我们自动生成 //使用save方法将实体对象持久化到数据库中 session.save(student); } @Test public void testFind(){ Student student = session.get(Student.class,1L); System.out.println(student); } @Test public void testUpdate(){ Student student = session.get(Student.class,1L); student.setName("Administrator"); student.setAge(20); session.update(student);// session.saveOrUpdate(student); 可以使用这两个方法更新数据,后者相比前者,可以在你不确定是更新还是添加数据的时候交由Hibernate去判断并调用合适的方法 } @Test public void testDelete(){ Student student = new Student(); student.setId(1L); session.delete(student); //session.delete(session.get(Student.class,1L)); } }