Hibernate注解配置

2021-07-01 03:05

阅读:607

标签:aec   tom   gen   配置   host   plugin   ack   nec   display   

1.注解方式:

注解的方式与xml很很多类似:

首先是需要在pom文件中加入4个jar包:

技术分享技术分享
 1 project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   modelVersion>4.0.0modelVersion>
 4   groupId>cn.yunhegroupId>
 5   artifactId>hibernate3artifactId>
 6   packaging>warpackaging>
 7   version>1.0-SNAPSHOTversion>
 8   name>hibernate3 Maven Webappname>
 9   url>http://maven.apache.orgurl>
10   dependencies>
11     dependency>
12       groupId>junitgroupId>
13       artifactId>junitartifactId>
14       version>4.12version>
15       scope>testscope>
16     dependency>
17 
18     dependency>
19       groupId>javax.servletgroupId>
20       artifactId>javax.servlet-apiartifactId>
21       version>3.1.0version>
22       scope>providedscope>
23     dependency>
24 
25     dependency>
26       groupId>mysqlgroupId>
27       artifactId>mysql-connector-javaartifactId>
28       version>5.1.6version>
29     dependency>
30 
31     dependency>
32       groupId>org.apache.strutsgroupId>
33       artifactId>struts2-coreartifactId>
34       version>2.3.31version>
35     dependency>
36 
37     dependency>
38       groupId>javax.servletgroupId>
39       artifactId>jstlartifactId>
40       version>1.2version>
41     dependency>
42 
43     dependency>
44       groupId>org.apache.strutsgroupId>
45       artifactId>struts2-dojo-pluginartifactId>
46       version>2.3.16version>
47     dependency>
48 
49 
50 
51     dependency>
52       groupId>org.hibernategroupId>
53       artifactId>hibernate-coreartifactId>
54       version>3.5.0-Finalversion>
55     dependency>
56 
57     dependency>
58       groupId>org.hibernategroupId>
59       artifactId>hibernate-annotationsartifactId>
60       version>3.5.0-Finalversion>
61     dependency>
62 
63     dependency>
64       groupId>org.slf4jgroupId>
65       artifactId>slf4j-log4j12artifactId>
66       version>1.5.8version>
67     dependency>
68 
69     dependency>
70       groupId>org.javassistgroupId>
71       artifactId>javassistartifactId>
72       version>3.13.0-GAversion>
73     dependency>
74   dependencies>
75   build>
76     finalName>hibernate3finalName>
77     plugins>
78       plugin>
79         groupId>org.eclipse.jettygroupId>
80         artifactId>jetty-maven-pluginartifactId>
81         version>9.3.14.v20161028version>
82       plugin>
83     plugins>
84   build>
85 project>
pom.xml

 

下面是不同的地方:

(1):hibernate.hbm.xml 文件中把引用:xxx.hbm.xml改为引用实体类:

     即把:

改为:

(2):获取SessionFactory方式发生了变化:

      即:由SessionFactory sf = new Configuration().configure().buildSessionFactory()

    改为:SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory()

(3):注解方式不需要在xxx.hbm.xml把实体类与表进行映射。而采用在实体类中进行注解。

注意:

(1):如果实体类属性名与表字段名不一致的时候,要么都注解在属性前,要么都注解在get方法前。不能部分注解在属性前,部分注解在方法前。

 (2):如果实体类属性名与表字段名一致的时候,可以部分注解在属性前,部分注解在方法前。

 (3):如果在实体类中某些属性不注解:(属性和get都不写注解),默认为表字段名与实体类属性名一致。

 (4):如果实体类的某个成员属性不需要存入数据库中,使用@Transient 进行注解就可以了。即类似于:(xxx.hbm.Xml配置中的某些字段不写(就是不需要对这个成员属性进行映射))

 (5):表名称可以在实体类前进行注解。

 (6):所有这些注解在:javax.persistence包下。而不是在hibernate包中。

2.单向一对多、单向多对一、双向多对一

1.实体类配置

技术分享技术分享
 1 package cn.yunhe.entity;
 2 
 3 import javax.persistence.*;
 4 import java.io.Serializable;
 5 
 6 
 7 @Entity
 8 @Table(name = "jd")
 9 public class Jd {//街道
10     private int jdid;
11     private String jdname;
12     private Qx qx;//区县
13 
14     @Id
15     @GeneratedValue
16     @Column(name = "jdid")
17     public int getJdid() {
18         return jdid;
19     }
20 
21     public void setJdid(int jdid) {
22         this.jdid = jdid;
23     }
24 
25     @Column(name = "jdname")
26     public String getJdname() {
27         return jdname;
28     }
29 
30     public void setJdname(String jdname) {
31         this.jdname = jdname;
32     }
33 
34     @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
35     @JoinColumn(name = "qxid")
36     public Qx getQx() {
37         return qx;
38     }
39 
40     public void setQx(Qx qx) {
41         this.qx = qx;
42     }
43 }
Jd(街道)
技术分享技术分享
 1 package cn.yunhe.entity;
 2 
 3 import javax.persistence.*;
 4 import java.util.HashSet;
 5 import java.util.Set;
 6 
 7 @Entity
 8 @Table(name = "qx")//实体类映射表
 9 public class Qx {//区县
10     private int qxid;
11     private String qxname;
12     private Set jds=new HashSet();
13 
14     @Id
15     @GeneratedValue
16     @Column(name = "qxid")
17     public int getQxid() {
18         return qxid;
19     }
20 
21     public void setQxid(int qxid) {
22         this.qxid = qxid;
23     }
24 
25     @Column(name = "qxname")
26     public String getQxname() {
27         return qxname;
28     }
29 
30     public void setQxname(String qxname) {
31         this.qxname = qxname;
32     }
33 
34     //@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY ,mappedBy = "qx")//mappedBy里面写的是对象
35     //@JoinColumn(name ="qxid" ) 双向操作Qx一对多声明可以不需要@JoinColumn,但@OneToMany(...mappedBy="category")
36     public Set getJds() {
37         return jds;
38     }
39 
40     public void setJds(Set jds) {
41         this.jds = jds;
42     }
43 }
Qx(区县)
技术分享技术分享
 1 xml version="1.0" encoding="UTF-8"?>
 2 DOCTYPE hibernate-configuration
 3         PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 hibernate-configuration>
 6     session-factory>
 7         property name="hibernate.hbm2ddl.auto" >updateproperty>
 8         property name="dialect">org.hibernate.dialect.MySQLDialectproperty>
 9         property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
10         property name="connection.url">jdbc:mysql://localhost:3306/hibernateproperty>
11         property name="connection.username">rootproperty>
12         property name="connection.password">1234property>
13         property name="show_sql">trueproperty>
14 
15         mapping class="cn.yunhe.entity.Qx"/>
16         mapping class="cn.yunhe.entity.Jd"/>
17     session-factory>
18 hibernate-configuration>
hibernate.cfg.xml

2. 测试类

技术分享技术分享
 1 import cn.yunhe.entity.Jd;
 2 import cn.yunhe.entity.Qx;
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.cfg.AnnotationConfiguration;
 7 import org.hibernate.cfg.Configuration;
 8 import org.junit.After;
 9 import org.junit.Before;
10 import org.junit.Test;
11 
12 import java.util.List;
13 import java.util.Set;
14 
15 /**
16  * Created by Administrator on 2017/7/6.
17  */
18 public class Demo {
19     Session session=null;
20     Transaction tr=null;
21 
22     @Before
23     public void setUp(){
24         Configuration config=new AnnotationConfiguration().configure();
25         SessionFactory factory= config.buildSessionFactory();
26         session=factory.openSession();
27         tr=session.beginTransaction();
28     }
29     @Test
30     public void testQuery(){
31         List list = session.createQuery("from Qx").list();
32         for (Qx qx : list) {
33             System.out.println(qx.getQxname());
34         }
35     }
36 
37     @Test
38     //单向一对多(使用时注意只能在实体类一的一方建多的一方对象,不能两边都创建)
39     public void testOneToMany(){
40         Qx qx= (Qx) session.get(Qx.class,1);
41         System.out.println(qx.getQxname()+"下的街道有:");
42         Set set=qx.getJds();
43         for(Jd jd:set){
44             System.out.println(jd.getJdname());
45         }
46     }
47     @Test
48     //单向多对一 /双向多对一(使用时注意只能在实体类多的一方建一的一方对象,不能两边都创建)
49     public void testManyToOne(){
50         Jd jd= (Jd) session.get(Jd.class,1);
51         System.out.println(jd.getJdname()+"属于");
52         System.out.println(jd.getQx().getQxname());
53     }
54 
55 
56     @After
57     public void tearDowm(){
58         session.close();
59     }
60 }
Demo

3.双向多对多

1.实体类

 

技术分享技术分享
 1 package cn.yunhe.entity;
 2 
 3 import javax.persistence.*;
 4 import java.util.HashSet;
 5 import java.util.Set;
 6 
 7 @Entity
 8 @Table(name = "student")
 9 public class Student {//学生表
10     private int id;
11     private String name;
12     public Set teachers =new HashSet();//互相建对方的set集合
13 
14     @Id
15     @GeneratedValue
16     @Column(name = "id")
17     public int getId() {
18         return id;
19     }
20 
21     public void setId(int id) {
22         this.id = id;
23     }
24 
25     @Column(name = "name")
26     public String getName() {
27         return name;
28     }
29 
30     public void setName(String name) {
31         this.name = name;
32     }
33 
34     @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
35     //配置中间表,并将外键对照起来
36     @JoinTable(name = "student_teacher",
37             joinColumns = @JoinColumn(name = "studentid"),
38             inverseJoinColumns = @JoinColumn(name ="teacherid"))
39     public Set getTeachers() {
40         return teachers;
41     }
42 
43     public void setTeachers(Set teachers) {
44         this.teachers = teachers;
45     }
46 }
student

 

技术分享技术分享
 1 package cn.yunhe.entity;
 2 
 3 import javax.persistence.*;
 4 import java.util.HashSet;
 5 import java.util.Set;
 6 
 7 
 8 @Entity
 9 @Table(name = "teacher")
10 public class Teacher {//教师
11     private  int id;
12     private String name;
13     public Set students =new HashSet();//互相建对方的集合
14 
15     @Id
16     @GeneratedValue
17     @Column(name = "id")
18     public int getId() {
19         return id;
20     }
21 
22     public void setId(int id) {
23         this.id = id;
24     }
25 
26     @Column(name = "name")
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         this.name = name;
33     }
34 
35     @ManyToMany(cascade = CascadeType.ALL,
36                 fetch = FetchType.LAZY,mappedBy = "teachers")
37     public Set getStudents() {
38         return students;
39     }
40 
41     public void setStudents(Set students) {
42         this.students = students;
43     }
44 }
teacher

2.测试类

技术分享技术分享
 1 import cn.yunhe.entity.Jd;
 2 import cn.yunhe.entity.Qx;
 3 import cn.yunhe.entity.Student;
 4 import cn.yunhe.entity.Teacher;
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.hibernate.Transaction;
 8 import org.hibernate.cfg.AnnotationConfiguration;
 9 import org.hibernate.cfg.Configuration;
10 import org.junit.After;
11 import org.junit.Before;
12 import org.junit.Test;
13 
14 import java.util.List;
15 import java.util.Set;
16 
17 /**
18  * Created by Administrator on 2017/7/6.
19  */
20 public class Demo {
21     Session session=null;
22     Transaction tr=null;
23 
24     @Before
25     public void setUp(){
26         Configuration config=new AnnotationConfiguration().configure();
27         SessionFactory factory= config.buildSessionFactory();
28         session=factory.openSession();
29         tr=session.beginTransaction();
30     }
31 
32 
33     @Test
34     //双向多对多(要有中间表,实体类互相建对方的对象的Set集合)
35     public  void testManyToMany(){
36         //根据学生查老师
37         Student student= (Student) session.get(Student.class,5);
38         System.out.println("学生:"+student.getName()+"的老师有:");
39         Set teachers=student.getTeachers();
40         for (Teacher t:teachers){
41             System.out.println(t.getName());
42         }
43 
44         //根据老师查学生
45         Teacher teacher= (Teacher) session.get(Teacher.class,4);
46         System.out.println("老师:"+teacher.getName()+"的学生有:");
47         Set students=teacher.getStudents();
48         for (Student s:students){
49             System.out.println(s.getName());
50         }
51     }
52 
53     @After
54     public void tearDowm(){
55         session.close();
56     }
57 }
Demo

3.主配置文件

技术分享技术分享
 1 xml version="1.0" encoding="UTF-8"?>
 2 DOCTYPE hibernate-configuration
 3         PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 hibernate-configuration>
 6     session-factory>
 7         property name="hibernate.hbm2ddl.auto" >updateproperty>
 8         property name="dialect">org.hibernate.dialect.MySQLDialectproperty>
 9         property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
10         property name="connection.url">jdbc:mysql://localhost:3306/hibernateproperty>
11         property name="connection.username">rootproperty>
12         property name="connection.password">1234property>
13         property name="show_sql">trueproperty>
14       
15         mapping class="cn.yunhe.entity.Student"/>
16         mapping class="cn.yunhe.entity.Teacher"/>
17 
18     session-factory>
19 hibernate-configuration>
hibernate.cfg.xml

 

 

Hibernate注解配置

标签:aec   tom   gen   配置   host   plugin   ack   nec   display   

原文地址:http://www.cnblogs.com/liuyingke/p/7134092.html


评论


亲,登录后才可以留言!