利用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>
- 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语句获取一批对象实例或集合。
- 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());
- }
- }
转自:http://blog.csdn.net/madison__/article/details/55677099