Hibernate的註解和檢索
阿新 • • 發佈:2017-10-31
ror finall gets restrict ner 映射關系 generate pojo line
Hibernate是一個開放源代碼的對象關系映射框架,它對JDBC進行了非常輕量級的對象封裝,它將POJO與數據庫表建立映射關系,是一個全自動的orm框架,hibernate可以自動生成SQL語句,自動執行,使得Java程序員可以隨心所欲的使用對象編程思維來操縱數據庫。 Hibernate可以應用在任何使用JDBC的場合,既可以在Java的客戶端程序使用,也可以在Servlet/JSP的Web應用中使用,最具革命意義的是,Hibernate可以在應用EJB的J2EE架構中取代CMP,完成數據持久化的重任。
註解:新聞表和評論表
comment.java
package com.cn.pojo;import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne;import javax.persistence.Table; @Entity @Table(name="t_comment") public class Comment implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String commentContent; @ManyToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY,targetEntity=News.class) @JoinColumn(name="news_id",nullable=false) private News news; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCommentContent() { return commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } public News getNews() { return news; } public void setNews(News news) { this.news = news; } public Comment() { super(); } public Comment(String commentContent) { super(); this.commentContent = commentContent; } }
News.java
package com.cn.pojo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="t_news") public class News implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String title; private String content; @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,targetEntity=Comment.class,mappedBy="news") private Set<Comment> comments=new HashSet<Comment>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public News() { super(); } public News(String title, String content) { super(); this.title = title; this.content = content; } public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; } }
HibernateSessionFactory.java
package com.cn.utilts; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); private static ServiceRegistry serviceRegistry; static { try { configuration.configure(); serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); try { sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory(); } catch (Exception e) { StandardServiceRegistryBuilder.destroy(serviceRegistry); e.printStackTrace(); } } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); try { sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory(); } catch (Exception e) { StandardServiceRegistryBuilder.destroy(serviceRegistry); e.printStackTrace(); } } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
測試類Test.java
package com.cn.test; import javax.persistence.Entity; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import com.cn.pojo.Comment; import com.cn.pojo.News; @Entity public class Test { @org.junit.Test public void test1(){ Configuration configuration = new AnnotationConfiguration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); try { News news = new News("鍐滆錘鏍囬","鍐滆錘鍐呭"); Comment comment1 = new Comment("璇勮1銆傘?傘??"); Comment comment2 = new Comment("璇勮2銆傘?傘??"); comment1.setNews(news); comment2.setNews(news); session.save(comment1); session.save(comment2); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); }finally{ session.close(); } } }
檢索:HQL
@org.junit.Test public void test1(){ Configuration configuration = new AnnotationConfiguration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); //獲取session對象 Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); try { //編寫hql語句 String hql = "from Customer c where c.name=? and c.password=?"; //獲取query對象 Query query = session.createQuery(hql).setString(0, "xxx").setString(1, "123456"); //動態綁定參數 /*query.setString(0, "xxx"); query.setString(1, "123456");*/ //操作query List<Customer> customers = query.list(); for(Customer customer:customers){ System.out.println("name="+customer.getName()); } transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally{ session.close(); } }
QBC
@org.junit.Test public void test7(){ Configuration configuration = new AnnotationConfiguration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); //獲取session對象 Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); try { //select * from tb_customer Criteria criteria = session.createCriteria(Customer.class).add(Restrictions.like("name", "%傑")).add(Restrictions.eq("password", "123456")); //創建條件 //name like "%傑" //password = "123456" //Criterion c1 = Restrictions.like("name", "%傑"); //Criterion c2 = Restrictions.eq("password", "123456"); //將條件添加到sql語句裏 //criteria.add(c1); //criteria.add(c2); List<Customer> customers = criteria.list(); for(Customer customer:customers){ System.out.println("name="+customer.getName()); } transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally{ session.close(); } }
Hibernate的註解和檢索