zoukankan      html  css  js  c++  java
  • Hibernate注解配置

    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.0</modelVersion>
     4   <groupId>cn.yunhe</groupId>
     5   <artifactId>hibernate3</artifactId>
     6   <packaging>war</packaging>
     7   <version>1.0-SNAPSHOT</version>
     8   <name>hibernate3 Maven Webapp</name>
     9   <url>http://maven.apache.org</url>
    10   <dependencies>
    11     <dependency>
    12       <groupId>junit</groupId>
    13       <artifactId>junit</artifactId>
    14       <version>4.12</version>
    15       <scope>test</scope>
    16     </dependency>
    17 
    18     <dependency>
    19       <groupId>javax.servlet</groupId>
    20       <artifactId>javax.servlet-api</artifactId>
    21       <version>3.1.0</version>
    22       <scope>provided</scope>
    23     </dependency>
    24 
    25     <dependency>
    26       <groupId>mysql</groupId>
    27       <artifactId>mysql-connector-java</artifactId>
    28       <version>5.1.6</version>
    29     </dependency>
    30 
    31     <dependency>
    32       <groupId>org.apache.struts</groupId>
    33       <artifactId>struts2-core</artifactId>
    34       <version>2.3.31</version>
    35     </dependency>
    36 
    37     <dependency>
    38       <groupId>javax.servlet</groupId>
    39       <artifactId>jstl</artifactId>
    40       <version>1.2</version>
    41     </dependency>
    42 
    43     <dependency>
    44       <groupId>org.apache.struts</groupId>
    45       <artifactId>struts2-dojo-plugin</artifactId>
    46       <version>2.3.16</version>
    47     </dependency>
    48 
    49 
    50 <!--以下四个包,缺一不可-->
    51     <dependency>
    52       <groupId>org.hibernate</groupId>
    53       <artifactId>hibernate-core</artifactId>
    54       <version>3.5.0-Final</version>
    55     </dependency>
    56 
    57     <dependency>
    58       <groupId>org.hibernate</groupId>
    59       <artifactId>hibernate-annotations</artifactId>
    60       <version>3.5.0-Final</version>
    61     </dependency>
    62 
    63     <dependency>
    64       <groupId>org.slf4j</groupId>
    65       <artifactId>slf4j-log4j12</artifactId>
    66       <version>1.5.8</version>
    67     </dependency>
    68 
    69     <dependency>
    70       <groupId>org.javassist</groupId>
    71       <artifactId>javassist</artifactId>
    72       <version>3.13.0-GA</version>
    73     </dependency>
    74   </dependencies>
    75   <build>
    76     <finalName>hibernate3</finalName>
    77     <plugins>
    78       <plugin>
    79         <groupId>org.eclipse.jetty</groupId>
    80         <artifactId>jetty-maven-plugin</artifactId>
    81         <version>9.3.14.v20161028</version>
    82       </plugin>
    83     </plugins>
    84   </build>
    85 </project>
    pom.xml

    下面是不同的地方:

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

         即把:<mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/>

    改为:<mapping class="com.wsw.hibernate.model.Teacher" />

    (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<Jd> jds=new HashSet<Jd>();
    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<Jd> getJds() {
    37         return jds;
    38     }
    39 
    40     public void setJds(Set<Jd> 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" >update</property><!--自动生成数据库表-->
     8         <property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--数据库方言-->
     9         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    10         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    11         <property name="connection.username">root</property>
    12         <property name="connection.password">1234</property>
    13         <property name="show_sql">true</property><!--显示sql-->
    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<Qx> 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<Jd> 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<Teacher> teachers =new HashSet<Teacher>();//互相建对方的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<Teacher> getTeachers() {
    40         return teachers;
    41     }
    42 
    43     public void setTeachers(Set<Teacher> 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<Student> students =new HashSet<Student>();//互相建对方的集合
    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<Student> getStudents() {
    38         return students;
    39     }
    40 
    41     public void setStudents(Set<Student> 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<Teacher> 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<Student> 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" >update</property><!--自动生成数据库表-->
     8         <property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--数据库方言-->
     9         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    10         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    11         <property name="connection.username">root</property>
    12         <property name="connection.password">1234</property>
    13         <property name="show_sql">true</property><!--显示sql-->
    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

     

  • 相关阅读:
    TypeError: Object(…) is not a function
    解决 OSError: [WinError 126] 找不到指定的模块
    LeetCode——和等于 k 的最长子数组长度
    LeetCode——判断子序列
    LeetCode——递增的三元子序列
    LeetCode——字符串相乘
    LeetCode——课程安排 IV
    LeetCode——最小移动次数使数组元素相等
    同源时钟、同相位时钟、同时钟域
    C++ 创建动态二维数组 使用vect<vec> 并初始化为0
  • 原文地址:https://www.cnblogs.com/liuyingke/p/7134092.html
Copyright © 2011-2022 走看看