hibernate Annotation 以及注解版的数据关联 4.4

目的是不写xxx.hbm.xml映射文件,使用注解

主配置文件还是要有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:///hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        
        <!-- 方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- c3p0数据源 -->
        <property name="c3p0.max_size">10</property>
        <property name="c3p0.min_size">2</property>
        <property name="c3p0.timeout">5000</property>
        <property name="c3p0.max_statements">100</property>
        <property name="c3p0.idle_test_period">3000</property>
        <property name="c3p0.acquire_increment">2</property>
        <property name="c3p0.validate">false</property>
        
        <property name="show_sql">true</property>
        <property name="current_session_context_class">thread</property>
        
        <!-- 开启二级缓存 使用EhCache实现-->
        <property name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        
        
        <!-- 不同的是这里,不写映射文件,而是完全限定名 -->
        <mapping class="com.kaishengit.pojo.User"/>
        <mapping class="com.kaishengit.pojo.Address"/>
        <mapping class="com.kaishengit.pojo.Teacher"/>
        <mapping class="com.kaishengit.pojo.Student"/>
        <mapping class="com.kaishengit.pojo.Employee"/>
        <mapping class="com.kaishengit.pojo.Dept"/>
        <mapping class="com.kaishengit.pojo.Person"/>
        <mapping class="com.kaishengit.pojo.Card"/>
        <mapping class="com.kaishengit.pojo.Account"/>
        <!-- 
        <mapping resource="com/kaishengit/pojo/User.hbm.xml"/>
        <mapping resource="com/kaishengit/pojo/Address.hbm.xml"/>
        <mapping resource="com/kaishengit/pojo/Person.hbm.xml"/>
        <mapping resource="com/kaishengit/pojo/Card.hbm.xml"/>
        <mapping resource="com/kaishengit/pojo/Employee.hbm.xml"/>
        <mapping resource="com/kaishengit/pojo/Dept.hbm.xml"/>
        <mapping resource="com/kaishengit/pojo/Student.hbm.xml"/>
        <mapping resource="com/kaishengit/pojo/Teacher.hbm.xml"/>
         -->
    </session-factory>
        
        
</hibernate-configuration>

-------------------------------------------------------------------
-------------------------------------------------------------------

一对多,多对一 记得添加到主配置文件中去

取而代之的是在类上注解

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity// 表示这是一个pojo类 
@Table(name="user")// 与数据库中表对应,表名和类名相同的可以不写 
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)/*加入缓存  */
public class User {
    
    @Id/*放在这个属性上,表示这个属性在数据库中是主键,如果属性的名字和数据库中的
        主键不一样,要加注解@column(name="id")*/
    //@column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)/* 主键生成策略*/
    private Integer id;
    
    
    /*普通属性不用管,自动映射,但是如果列名和属性名不一样要加column */
    //@Column(name="username")
    private String username;
    private String password;
    /* 多的一方维护关系,user不用管,mappedBy="user"(user是自己在对方类中属性的名字)相当于inverse,放弃关系维护 */
    @OneToMany(mappedBy="user")
    @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)// 加入缓存 
    @OrderBy("id desc")//排序
    private Set<Address> addressSet;
}
@Entity
@Table
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)/* 加入缓存 */
public class Address {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String address;
    @ManyToOne//多对一
    @JoinColumn(name="userid")//指定外键
    private User user;
}

---------------------------------------------------------------
---------------------------------------------------------------
---------------------------------------------------------------

多对多 ,记得添加到主配置文件中去

@Entity
@Table
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class Student {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String name;
    
    @ManyToMany                            /*自己在关系表中的外键*/        /* 对方在关系表中的外键*/
    @JoinTable(name="student_teacher",joinColumns={@JoinColumn(name="sid")},inverseJoinColumns={@JoinColumn(name="tid")})
    private Set<Teacher> teachers;

}
@Entity
@Table
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class Teacher {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String name;
    @ManyToMany(mappedBy="teachers")//放弃维护 
    @OrderBy("id desc")
    @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
    private Set<Student> students;
    
    
}

--------------------------------------------------------
--------------------------------------------------------

一对一

第一种一对一

person和card,card的id即作为主键,又作为外键

@Entity
@Table
public class Person {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String name;
    
    @OneToOne
    @PrimaryKeyJoinColumn/*告诉card,主键是靠着我(person) 产生的 */
    private Card card;
@Entity
@Table
public class Card {
/* JPA中的主键生成策略只有四种,不支持外键生成器 所以写一个生成器GenericGenerator,名字叫FK
    生成策略叫foreign,
        这个person是属性,指明用card这个类的person属性对应的表的主键作外键*/
    @Id
    @GenericGenerator(name="FK",strategy="foreign",parameters={@Parameter(name="property",value="person")})
    @GeneratedValue(generator="FK")// 指定多用的生成器
    private Integer id;
    private String cardnum;
    
    @OneToOne(mappedBy="card")
    @PrimaryKeyJoinColumn
    private Person person;
    

第二种一对一,是一对多或者多对一的特殊情况

dept和Employee,dept中有eid,Employee中有deptid

@Entity
@Table
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String name;
    @ManyToOne
    @JoinColumn(name="deptid")
    private Dept dept;
}
@Entity
@Table
public class Dept {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String name;
    @ManyToOne
    @JoinColumn(name="eid")
    private Employee employee;


}

----------------------------------------------------------
-------------------------------------------------------
-----------------------------------------------------

id不想用自动增长型,想用UUID怎么设置主键生成策略?

@Entity
@Table
public class Account {

    
    private String id;
    private String name;
    
    @Id
    @GenericGenerator(name="myuuid",strategy="uuid")
    @GeneratedValue(generator="myuuid")
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    // 排除不进行持久化操作的属性 
    @Transient
    public String getNickName() {
        return "Hello,Jack";
    }
    
    
}

程序执行.不用生成UUID,只需要保存

session.beginTransaction();
        
        Account account = new Account();
        account.setName("hello");
        
        session.save(account);
        
        session.getTransaction().commit();

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。