关闭

Hibernate关联映射基于注解

标签: hibernatejava
153人阅读 评论(0) 收藏 举报
分类:
package com.dt.pojo;


import java.util.HashSet;
import java.util.Set;


import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;


@Entity
@Table(name="v_user")
public class User {
 
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String usercode;
private String username;

@OneToMany(targetEntity=Order.class, mappedBy="user", cascade=CascadeType.ALL)
private Set<Order> addresses = new HashSet<Order>();

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsercode() {
return usercode;
}
public void setUsercode(String usercode) {
this.usercode = usercode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}




}



package com.dt.pojo;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;


@Entity
@Table(name="v_order")
public class Order {
 
// 标识属性
@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
 
    private String no;
    
    private String ordername;
    
    private String ctime;


 // 记录该Address实体关联的Person实体
  @ManyToOne(targetEntity=User.class)
 // 使用@JoinColumns包含多个@JoinColumn定义外键列
  @JoinColumns({
  // 由于主表使用了复合主键(有多个主键列)
  // 因此需要使用多个@JoinColumn定义外键列来参照t_person表的多个主键列
  //referencedColumnName标注的是所关联表中的字段名  , nullable=false是这个字段在保存时必需有值
  @JoinColumn(name="user_id", referencedColumnName="id" , nullable=false)
  })
    private User user;
    
public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getNo() {
return no;
}


public void setNo(String no) {
this.no = no;
}


public String getOrdername() {
return ordername;
}


public void setOrdername(String ordername) {
this.ordername = ordername;
}


public String getCtime() {
return ctime;
}


public void setCtime(String ctime) {
this.ctime = ctime;
}


public User getUser() {
return user;
}


public void setUser(User user) {
this.user = user;
}
    
    
    
    
 
}














package com.dt.util;


import org.hibernate.Transaction;


import com.dt.pojo.Order;
import com.dt.pojo.User;
import org.hibernate.Session;






public class OrderManager
{
public static void main(String[] args)
{
OrderManager mgr = new OrderManager();
mgr.createAndStoreOrder();
HibernateUtil.sessionFactory.close();
}
private void createAndStoreOrder()
{
Session sess = HibernateUtil.currentSession();
Transaction tx = sess.beginTransaction();


User user  = new User();
user.setUsercode("BU001");
user.setUsername("测试用户");
 
Order order = new Order();
     order.setNo("001");
     order.setCtime("2016-06-02");
     order.setOrdername("订单名称1");
     order.setUser(user);
     
     
     Order order2 = new Order();
     order2.setNo("002");
     order2.setCtime("2016-06-03");
     order2.setOrdername("订单名称2");
     order2.setUser(user);
     
     sess.save(user);
     sess.save(order);
     sess.save(order2);


tx.commit();
HibernateUtil.closeSession();
}
}













package com.dt.util;


import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;


public class HibernateUtil
{
public static final SessionFactory sessionFactory;


static
{
try
{
// 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
Configuration cfg = new Configuration()
.configure();
// 以Configuration实例来创建SessionFactory实例
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}


// ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
public static final ThreadLocal<Session> session
= new ThreadLocal<Session>();


public static Session currentSession()
throws HibernateException
{
Session s = session.get();
// 如果该线程还没有Session,则创建一个新的Session
if (s == null)
{
s = sessionFactory.openSession();
// 将获得的Session变量存储在ThreadLocal变量session里
session.set(s);
}
return s;
}


public static void closeSession()
throws HibernateException
{
Session s = session.get();
if (s != null)
s.close();
session.set(null);
}
}











<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置文件的根元素 -->
<hibernate-configuration>
<session-factory>
<!-- 指定连接数据库所用的驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<!-- 指定连接数据库的用户名 -->
<property name="connection.username">root</property>
<!-- 指定连接数据库的密码 -->
<property name="connection.password">11111</property>
<!-- 指定连接池里最大连接数 -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- 指定连接池里最小连接数 -->
<property name="hibernate.c3p0.min_size">1</property>
<!-- 指定连接池里连接的超时时长 -->
<property name="hibernate.c3p0.timeout">5000</property>
<!-- 指定连接池里最大缓存多少个Statement对象 -->
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<!-- 指定数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.show_sql">true</property>
<!-- 根据需要自动创建数据库 -->
<property name="hbm2ddl.auto">update</property>
<!-- 罗列所有持久化类的类名 -->
<mapping class="com.dt.pojo.Order"/>
<mapping class="com.dt.pojo.User"/>
</session-factory>
</hibernate-configuration>






0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:33872次
    • 积分:1708
    • 等级:
    • 排名:千里之外
    • 原创:134篇
    • 转载:62篇
    • 译文:0篇
    • 评论:4条
    最新评论