利用Hibernate注解生成表
转自:http://blog.csdn.net/madison__/article/details/55677099
Hibernate4注释
@Entity(name = "tbl_user") 将一个类声明为一个实体bean(即一个持久化POJO类)
@Id注解则声明了该实体bean的标识属性,必填属性
@GenericGeneratorhibernate在JPA的基础上进行了扩展,可以用一下方式引入hibernate独有的主键生成策略。
@Column name解决属性名和字段名不对应 length限制字符串长度 unique , nullable , precision 数据长度, scale 无小数
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">
- <!-- Generated by MyEclipse Hibernate Tools. -->
- <hibernate-configuration>
- <session-factory>
- <property name="myeclipse.connection.profile">mysql</property>
- <property name="connection.url">
- jdbc:mysql://localhost:3306/forums
- </property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <property name="connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <property name="hibernate.current_session_context_class">thread</property>
- <property name="dialect">
- org.hibernate.dialect.MySQLDialect
- </property>
- <property name="show_sql">true</property>
- <property name="hibernate.current_session_context_class">thread</property>
- <!--设置自动生成表,如果表不存在就自动生成,如果表存在就更新表结构-->
- <property name="hibernate.hbm2ddl.auto">update</property>
- <!-- 连接池 配置 c3p0-->
- <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
- <!-- 在连接池中可用数据连接的最大数目 -->
- <property name="hibernate.c3p0.max_size">20</property>
- <!-- 在连接池中可用数据连接的最小数目 -->
- <property name="hibernate.c3p0.min_size">5</property>
- <!-- 设定数据库连接的过期时间,以秒为单位,如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除-->
- <property name="hibernate.c3p0.timeout">120</property>
- <!-- 每3000秒查询所有连接池的空闲连接以秒为单位 -->
- <property name="hibernate.c3p0.idle_test_period">3000</property>
- <!--当连接池里面的连接用完的时候,C3P0一下获取的新的连接数
- <property name="hibernate.c3p0.acquire_increment">2</property>
- 每次都验证连接是否可用
- <property name="hibernate.c3p0.validate">true</property> -->
- <!-- 映射文件引入 -->
- <mapping class="csdn.forum.model.TblUser" />
- <mapping class="csdn.forum.model.TblTopic" />
- <mapping class="csdn.forum.model.TblBoard" />
- <mapping class="csdn.forum.model.TblReply" />
- </session-factory>
- </hibernate-configuration>
解析文件hibernate.hbm.xml的类HibernateSessionFactory.java
- package csdn.forum.util;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.service.ServiceRegistry;
- public class HibernateSessionFactory {
- static Configuration cfg;
- static SessionFactory sessionFactory;
- static ServiceRegistry serviceRegistry;
- static {
- cfg = new Configuration().configure();// 默认找文件hibernate.hbm.xml
- // 创建服务注册对象
- serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
- cfg.getProperties()).build();
- // 创建Factory工厂
- sessionFactory = cfg.buildSessionFactory(serviceRegistry);
- }
- // 获取session对象
- public static Session getSession() {
- // 打开session
- return sessionFactory.getCurrentSession();
- }
- }
fetch在Hibernate里用时默认值:FetchType.LAZY,它要求程序运行时延迟加载所有的集合和实体。
fetch设置为FetchType.EAGER,它提示程序在首次访问数据时应马上加载所有的集合和实体mappedBy默认值:如果关系是单向的,则该关联提供程序确定拥有该关系的字段。如果关系是双向的,则将关联相反(非拥有)方上的mappedBy元素设置为拥有此关系的字段或属性的名称
@BatchSize(size=10) 对查询抓取的优化方案,通过指定一个主键或外键列表,Hibernate使用单条SELECT语句获取一批对象实例或集合。
TblBoard.java
- package csdn.forum.model;
- import java.util.ArrayList;
- import java.util.List;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.ManyToOne;
- import javax.persistence.OneToMany;
- import org.hibernate.annotations.GenericGenerator;
- @Entity(name = "tbl_board")
- public class TblBoard {
- private String id;
- private String name;
- private TblBoard parentBoard;
- private List<TblBoard> board = new ArrayList<TblBoard>();
- private List<TblTopic> topics=new ArrayList<TblTopic>();
- // @id必填
- @GenericGenerator(name = "generator", strategy = "uuid.hex")
- // hibernate独有的16进制算法
- @Id
- @GeneratedValue(generator = "generator")
- @Column(name = "id", unique = true, nullable = false, length = 32)
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- @Column(name ="name")
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @ManyToOne(cascade = {CascadeType.ALL})
- @JoinColumn(name = "parent_id")
- public TblBoard getParentBoard() {
- return parentBoard;
- }
- public void setParentBoard(TblBoard parentBoard) {
- this.parentBoard = parentBoard;
- }
- @OneToMany(cascade = {CascadeType.ALL},fetch = FetchType.LAZY,mappedBy = "parentBoard")//在1这方加入@OneToMany(cascade = {CascadeType.ALL},mappedBy = "user") ,只调用session.sa//ve(user);
- //在多这方加入@ManyToOne(cascade = {CascadeType.ALL}) @JoinColumn(name = "user_id"),只调用s//ession.save(topic);
- public List<TblBoard> getBoard() {
- return board;
- }
- public void setBoard(List<TblBoard> board) {
- this.board = board;
- }
- @OneToMany(cascade = {CascadeType.ALL},fetch = FetchType.LAZY,mappedBy = "board")
- public List<TblTopic> getTopics() {
- return topics;
- }
- public void setTopics(List<TblTopic> topics) {
- this.topics = topics;
- }
- }
TblReply.Java
- package csdn.forum.model;
- import java.util.Date;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.ManyToOne;
- import javax.persistence.Temporal;
- import javax.persistence.TemporalType;
- import org.hibernate.annotations.GenericGenerator;
- @Entity(name = "tbl_reply")
- public class TblReply{
- private String id;
- private String title;
- private String content;
- private Date publishTime;
- private Date modifyTime;
- private TblUser user;
- private TblTopic tblTopic;
- @GenericGenerator(name = "generator", strategy = "uuid.hex")
- @Id
- @GeneratedValue(generator = "generator")
- @Column(name = "id", unique = true, nullable = false, length = 32)
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- @Column(name = "title", length = 32)
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- @Column(name = "content", length = 2000)
- public String getContent() {
- return content;
- }
- public void setContent(String content) {
- this.content = content;
- }
- @Temporal(TemporalType.DATE)
- @Column(name = "publishTime")
- public Date getPublishTime() {
- return publishTime;
- }
- public void setPublishTime(Date publishTime) {
- this.publishTime = publishTime;
- }
- @Temporal(TemporalType.DATE)
- @Column(name = "modifyTime")
- public Date getModifyTime() {
- return modifyTime;
- }
- public void setModifyTime(Date modifyTime) {
- this.modifyTime = modifyTime;
- }
- @ManyToOne(cascade = {CascadeType.ALL})
- @JoinColumn(name = "user_id")
- public TblUser getUser() {
- return user;
- }
- public void setUser(TblUser user) {
- this.user = user;
- }
- @ManyToOne(cascade = {CascadeType.ALL})
- @JoinColumn(name = "topic_id")
- public TblTopic getTblTopic() {
- return tblTopic;
- }
- public void setTblTopic(TblTopic tblTopic) {
- this.tblTopic = tblTopic;
- }
- }
TblTopic.java
- package csdn.forum.model;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.ManyToOne;
- import javax.persistence.OneToMany;
- import javax.persistence.Temporal;
- import javax.persistence.TemporalType;
- import org.hibernate.annotations.BatchSize;
- import org.hibernate.annotations.GenericGenerator;
- @Entity(name = "tbl_topic")
- public class TblTopic {
- private String id;
- private String title;
- private String content;
- private Date pubishTime;
- private Date modifyTime;
- private TblUser user;
- private TblBoard board;
- private List<TblReply> replys=new ArrayList<TblReply>();
- @GenericGenerator(name = "generator", strategy = "uuid.hex")
- @Id
- @GeneratedValue(generator = "generator")
- @Column(name = "id", unique = true, nullable = false, length = 32)
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- @Column(name = "title", length = 32)
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- @Column(name = "content", length = 2000)
- public String getContent() {
- return content;
- }
- public void setContent(String content) {
- this.content = content;
- }
- @Temporal(TemporalType.DATE)
- @Column(name = "publishTime")
- public Date getPubishTime() {
- return pubishTime;
- }
- public void setPubishTime(Date pubishTime) {
- this.pubishTime = pubishTime;
- }
- @Temporal(TemporalType.DATE)
- @Column(name = "modifyTime")
- public Date getModifyTime() {
- return modifyTime;
- }
- public void setModifyTime(Date modifyTime) {
- this.modifyTime = modifyTime;
- }
- // 多这方映射user_id
- @ManyToOne(cascade = {CascadeType.ALL})
- @JoinColumn(name = "user_id")
- public TblUser getUser() {
- return user;
- }
- public void setUser(TblUser user) {
- this.user = user;
- }
- @OneToMany(cascade = {CascadeType.ALL},fetch = FetchType.LAZY,mappedBy = "tblTopic")
- public List<TblReply> getReplys() {
- return replys;
- }
- public void setReplys(List<TblReply> replys) {
- this.replys = replys;
- }
- @ManyToOne(cascade = {CascadeType.ALL})
- @JoinColumn(name = "board_id")
- public TblBoard getBoard() {
- return board;
- }
- public void setBoard(TblBoard board) {
- this.board = board;
- }
- }
TblUser.java
- package csdn.forum.model;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.OneToMany;
- import javax.persistence.Temporal;
- import javax.persistence.TemporalType;
- import org.hibernate.annotations.GenericGenerator;
- @Entity(name="tbl_user")
- public class TblUser {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private String id;
- private String uname;
- private String upass;
- private String head;
- private Date regTime;
- private boolean gender;
- private List<TblTopic> topic=new ArrayList<TblTopic>();
- private List<TblReply> replies=new ArrayList<TblReply>();
- //@id必填
- @GenericGenerator(name = "generator", strategy = "uuid.hex")//hibernate独有的16进制算法
- @Id
- @GeneratedValue(generator = "generator")
- @Column(name = "id", unique = true, nullable = false, length = 32)
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- @Column (name="uname",length=20)
- public String getUname() {
- return uname;
- }
- public void setUname(String uname) {
- this.uname = uname;
- }
- @Column (name="upass",length=20)
- public String getUpass() {
- return upass;
- }
- public void setUpass(String upass) {
- this.upass = upass;
- }
- @Column (name="head")
- public String getHead() {
- return head;
- }
- public void setHead(String head) {
- this.head = head;
- }
- @Temporal(TemporalType.DATE)
- @Column(name = "regTime")
- public Date getRegTime() {
- return regTime;
- }
- public void setRegTime(Date regTime) {
- this.regTime = regTime;
- }
- @Column(name="gender",length=20)
- public boolean isGender() {
- return gender;
- }
- public void setGender(boolean gender) {
- this.gender = gender;
- }
- //现在是一的一方直接通过它映射user,user是多的这一方的属性
- // @OneToMany(mappedBy="user")
- @OneToMany(cascade = {CascadeType.ALL},fetch = FetchType.LAZY,mappedBy = "user")
- public List<TblTopic> getTopic() {
- return topic;
- }
- public void setTopic(List<TblTopic> topic) {
- this.topic = topic;
- }
- @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY,mappedBy="user")
- public List<TblReply> getReplies() {
- return replies;
- }
- public void setReplies(List<TblReply> replies) {
- this.replies = replies;
- }
- }
测试类TestUser.java
- package csdn.forum.test;
- import java.util.Date;
- import java.util.List;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.junit.Test;
- import csdn.forum.model.TblBoard;
- import csdn.forum.model.TblReply;
- import csdn.forum.model.TblTopic;
- import csdn.forum.model.TblUser;
- import csdn.forum.util.HibernateSessionFactory;
- public class TestUser {
- @Test
- public void save() {
- Session session = HibernateSessionFactory.getSession();
- session.getTransaction().begin();
- /*
- * //1.保存java板块包含jsp,ajax,struts2,hiberante子版块 TblBoard java =new
- * TblBoard(); java.setName("java");
- *
- * TblBoard jsp =new TblBoard(); jsp.setName("jsp"); TblBoard struts2
- * =new TblBoard(); struts2.setName("struts2"); TblBoard hiberante =new
- * TblBoard(); hiberante.setName("hiberante"); //相互持有
- * java.getBoard().add(jsp); java.getBoard().add(struts2);
- * java.getBoard().add(hiberante); jsp.setParentBoard(java);
- * struts2.setParentBoard(java); hiberante.setParentBoard(java);
- *
- *
- * session.save(java); session.getTransaction().commit();
- */
- // 2.利用csdn用户身份,在struts2板块下发表帖子
- /*
- * TblUser user=new TblUser(); user.setUname("csdn"); TblBoard
- * struts2=(TblBoard
- * )session.get(TblBoard.class,"2c96c05e44da48600144da4861f60002");
- * TblTopic topic=new TblTopic(); topic.setTitle("struts TblBoard");
- * topic.setUser(user); topic.setBoard(struts2); topic.setPubishTime(new
- * Date()); user.getTopic().add(topic); session.save(topic);
- * session.getTransaction().commit();
- */
- /*
- * //3.利用admin用户身份,给帖子回帖 TblUser user=new TblUser();
- * user.setUname("admin"); TblTopic topic1=(TblTopic)
- * session.get(TblTopic.class,"2c96c05e44da44660144da4469390000");
- * TblReply reply=new TblReply(); reply.setTitle("reply title");
- * reply.setUser(user); user.getReplies().add(reply);
- * reply.setTblTopic(topic1); topic1.getReplys().add(reply);
- * session.getTransaction().commit();
- */
- // 4.利用admin用户身份,修改回帖内容
- /*
- * Query query=session.createQuery(
- * "from csdn.forum.model.TblReply r where r.user.uname='admin'");
- * TblReply reply=(TblReply) query.list().get(0);
- * reply.setTitle("update"); session.save(reply);
- * session.getTransaction().commit();
- */
- // 5.利用admin用户身份,查看回帖//根据帖子查看回帖,查看下面的所有回帖
- /*
- * Query query=session.createQuery(
- * "from csdn.forum.model.TblReply t where t.user.uname='admin'");
- * List<TblReply> lisst=query.list();
- *
- * for(TblReply tabl:lisst){ System.out.println("1111111111111");
- * System.out.println(tabl.getContent()); }
- * session.getTransaction().commit();
- */
- // 6.利用csdn用户身份,删除回帖,条件限制为有回帖存在不允许删除
- /*
- * Query query1=session.createQuery(
- * "from csdn.forum.model.TblTopic t where t.user.uname='csdn'");
- * TblTopic topic1=(TblTopic) query1.list().get(0);
- * if(topic1.getReplys().size()==0){ session.delete(topic1); }else{
- * System.out.println("提示不能删除"); }
- *
- * session.getTransaction().commit();
- */
- // 7.统计struts2板块下的发帖数
- // Query
- // query2=session.createQuery("select count(*) from csdn.forum.model.TblTopic t where t.board.name='struts2'");
- /*
- * Query query2 = session.createQuery(
- * " from csdn.forum.model.TblTopic t where t.board.name='struts2'");
- *
- * System.out.println(query2.list().size()+"---"); //
- * System.out.println(query2.list().get(0)); //
- * System.out.println(query2.list().get(1)); //
- * System.out.println(query2.list().get(2));
- * session.getTransaction().commit();
- */
- // 8.查询struts2板块下所有帖子按时间倒序排列
- /*
- * Query query=session.createQuery(
- * "from csdn.forum.model.TblTopic t where t.board.name='struts2' order by t.pubishTime desc"
- * ); //System.out.println(query); for(int
- * i=0;i<query.list().size();i++){ TblTopic topic=(TblTopic)
- * query.list().get(i); System.out.println(topic.getTitle()); }
- */
- // 9.查询帖子下所有回帖,按时间倒序排列
- /*
- * Query query=session.createQuery(
- * "from csdn.forum.model.TblReply t where t.tblTopic.title='struts TblBoard' order by t.publishTime desc"
- * ); //System.out.println(query); for(int
- * i=0;i<query.list().size();i++){ TblReply topic=(TblReply)
- * query.list().get(i); System.out.println(topic.getTitle()); }
- */
- /*
- *
- * 查询父亲java板块
- * TblBoard board = (TblBoard) session.get(TblBoard.class,
- "2c96c05e44da48600144da4861dd0000");
- System.out.println(board);
- session.getTransaction().commit();*/
- // 10.查出最后发表帖子标题
- Query query = session
- .createQuery("from csdn.forum.model.TblTopic t order by t.pubishTime asc");
- // System.out.println(query);
- TblTopic topic=(TblTopic) query.list().get(query.list().size()-1);
- System.out.println(topic.getTitle());
- }
- }
利用Hibernate注解生成表的更多相关文章
- Hibernate用注解生成表
User.java实体来 package com.tao.pojo; import javax.persistence.Column; //用注解的方式生成表 import javax.persist ...
- 使用hibernate利用实体类生成表和利用表生成实体类
1,配置数据库,这里以oracle数据库为例.点击右侧Database图标:
- hibernate使用注解生成表,有时无法生成数据表的原因
待生成表中有字段“desc”或“descripe”等和hibernate关键字,导致和hibernate冲突
- Hibernate笔记②--hibernate类生成表、id生成策略、级联设置、继承映射
一.多表的一个关联关系 老师和学生是一对多的关系 student:tid属性 外键约束 对应teacher表中的id属性 teacher:id 在myeclipse的db窗口中选中两个表来生成类. ...
- hibernate注解创建表总是失败,显示表不存在
import java.io.Serializable; import javax.persistence.*; import org.hibernate.annotations.GenericGen ...
- 利用Xstream注解生成和解析xml
实体类: @XStreamAlias("person") public class PersonBean { @XStreamAlias("firstName&q ...
- java 利用Xstream注解生成和解析xml
https://www.oschina.net/code/snippet_116183_14202#23325
- hibernate如何配置自动生成表
hibernate自动生成表有两种方法: 1.直接写代码,通过方法来创建数据库表. 2.通过 hibernate.cfg.xml配置标签来创建数据表. 下面依次实现: 1.直接写代码,通过方法来创建数 ...
- Hibernate注解使用以及Spring整合
Hibernate注解使用以及Spring整合 原文转自:http://wanqiufeng.blog.51cto.com/409430/484739 (1) 简介: 在过去几年里,Hibernate ...
随机推荐
- nginx只允许域名访问,禁止ip访问
背景:为什么要禁止ip访问页面呢?这样做是为了避免其他人把未备案的域名解析到自己的服务器IP,而导致服务器被断网,我们可以通过禁止使用ip访问的方法,防止此类事情的发生. 解决方法:这里介绍修改配置文 ...
- Python 的数据表示
一.常量.变量和对象 1.常量:是指在程序的执行过程中不变的量.如:1,2,3,4,……,true.false 也有一些包含在模块中的用符号表示的常量,常用的如math模块中的pi和e,如: > ...
- 在php中修改cookie值遇到的奇怪问题
本想修改cookie的值比较简单,结果测试发现并不是. 刚开始实现cookie修改的思路:先删除以前的cookie值,再创建一个新的. setcookie('name',value,time()-1) ...
- rtp协议详解/rtcp协议详解
转自:http://www.cnblogs.com/li0803/archive/2010/11/20/1882792.html 1.简介 目前,在IP网络中实现实时语音.视频通信和应用已经成为网络应 ...
- Android AIDL Service 跨进程传递复杂数据
黑夜 黑夜给了我黑色的眼睛,我却用它寻找光明~ 传值方式 AIDL是同意跨进程传递值的,一般来说有三种方式: - 广播:这样的算是比較常见的一种方式了,传递小数据不错 - 文件:这个是保存到文件里.然 ...
- Leetcode--easy系列3
#26 Remove Duplicates from Sorted Array Given a sorted array, remove the duplicates in place such th ...
- WCF 动态调用(1)
很多时候,服务地址都不止一个的,这个时候就要动态去配置地址.配置Web.config,很麻烦 下面就看看怎样实现动态调用WCF. using System; using System.Collecti ...
- volatile关键字比较好的解释
http://www.tuicool.com/articles/IRvUJbN http://tengj.top/2016/05/06/threadvolatile4/?utm_source=tuic ...
- Help Tomisu UVA - 11440 难推导+欧拉函数,给定正整数N和M, 统计2和N!之间有多少个整数x满足,x的所有素因子都大于M (2<=N<=1e7, 1<=M<=N, N-M<=1E5) 输出答案除以1e8+7的余数。
/** 题目:Help Tomisu UVA - 11440 链接:https://vjudge.net/problem/UVA-11440 题意:给定正整数N和M, 统计2和N!之间有多少个整数x满 ...
- Oracle 数据库排错之 ORA-00600
[错误代码] ORA-00600 [问题描述] ORA-00600: [kcratr1_lastbwr]错误的处理办法 [问题分析] 出现该错误是因为系统强制关机造成的!症状为数据库无法打开! [问题 ...