利用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 ...
随机推荐
- (一)Shiro笔记——简介、 架构分析
1. Shiro是什么 Apache Shiro是一个强大灵活的开源安全框架,可以完全处理身份验证,授权,企业会话管理和加密. Apache Shiro的首要目标是易于使用和理解. 安全有时可能非常复 ...
- (二)Maven 基本概念——依赖、生命周期、仓库管理、聚合&继承
1. 依赖配置 1.1 依赖配置主要包含如下元素: <!--添加依赖配置--> <dependencies> <!--项目要使用到junit的jar包,所以在这里添加ju ...
- asp.net core mvc视频A:笔记5-1.路由规则
方法一:通过MapRoute方法,配置文件位置 小例子:如果所有路径都要在admin下,可以这样写 方法二:通过路由属性 相对路由 现在需要加/admin/home/index才能正常访问原来的默认页 ...
- 调用getChildFragmentManager时出现的Bug
异常: java.lang.IllegalStateException: Activity has been destroyed at android.support.v4.app.FragmentM ...
- sql server 常用函数 及 方法
返回受上一语句影响的行数: @@ROWCOUNT 语法@@ROWCOUNT 返回类型integer 注释任何不返回行的语句将这一变量设置为 0 ,如 IF 语句. 示例下面的示例执行 UPDATE 语 ...
- vue 跨域:使用vue-cli 配置 proxyTable 实现跨域问题
路径在/config/index.js 中,找到dev.proxyTable.如下配置示例: proxyTable: { '/api': { // 我要请求的地址 target: 'http://oa ...
- Notes from Data Guard
There are two types of Standby databases: 1, Physical standby database block-for-block basis the phy ...
- [ElasticSearch] 空间搜索 (一)
依据索引文档的地理坐标来进行搜索.Elasticsearch 也可以处理这种搜索.--空间搜索 一.为空间搜索准备映射 PUT my_space_test { "mappings" ...
- row format delimited fields terminated by ','
row format delimited fields terminated by ',' 以','结尾的行格式分隔字段
- Java并发编程(十三)同步容器类
同步容器类 Vector.HashTable,我用的很少:Vecotr的实现和ArrayList挺接近的,不同的是Vector中很多的方法都用synchronized进行了同步.在不强调线程安全地时候 ...