利用Hibernate注解生成表

Hibernate4注释

@Entity(name = "tbl_user")  将一个类声明为一个实体bean(即一个持久化POJO类)
@Id注解则声明了该实体bean的标识属性,必填属性
@GenericGeneratorhibernate在JPA的基础上进行了扩展,可以用一下方式引入hibernate独有的主键生成策略。
@Column   name解决属性名和字段名不对应 length限制字符串长度 unique , nullable , precision 数据长度, scale  无小数

hibernate.cfg.xml

      
      
      
      
      
      
        mysql  
          
            jdbc:mysql://localhost:3306/forums  
          
        root  
        root  
          
            com.mysql.jdbc.Driver  
          
        thread  
          
            org.hibernate.dialect.MySQLDialect  
          
        true  
        thread  
        update  
      
          
        org.hibernate.c3p0.internal.C3P0ConnectionProvider  
          
        20  
          
        5  
          
        120  
          
        3000  
      
          
          
              
           
            
           
            
      
      
      



解析文件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 board = new ArrayList();  
        private List topics=new ArrayList();  
        // @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 getBoard() {  
            return board;  
        }  
      
        public void setBoard(List board) {  
            this.board = board;  
        }  
        @OneToMany(cascade = {CascadeType.ALL},fetch = FetchType.LAZY,mappedBy = "board")  
        public List getTopics() {  
            return topics;  
        }  
      
        public void setTopics(List topics) {  
            this.topics = topics;  
        }  
      
    }  



利用Hibernate注解生成表_第1张图片

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;  
        }  
          
    }  


利用Hibernate注解生成表_第2张图片


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 replys=new ArrayList();  
          
        @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 getReplys() {  
            return replys;  
        }  
        public void setReplys(List 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;  
        }     
    }  






利用Hibernate注解生成表_第3张图片 

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  topic=new ArrayList();  
        private  List  replies=new ArrayList();  
      
        //@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 getTopic() {  
            return topic;  
        }  
      
        public void setTopic(List topic) {  
            this.topic = topic;  
        }  
      
        @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY,mappedBy="user")  
        public List getReplies() {  
            return replies;  
        }  
      
        public void setReplies(List replies) {  
            this.replies = replies;  
        }  
      
          
      
    }  



利用Hibernate注解生成表_第4张图片


测试类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 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



利用Hibernate注解生成表_第5张图片

你可能感兴趣的:(Hibernate)