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的注解和检索的更多相关文章

  1. Java、Hibernate(JPA)注解大全

    1.@Entity(name=”EntityName”) 必须,name为可选,对应数据库中一的个表 2.@Table(name=””,catalog=””,schema=””) 可选,通常和@Ent ...

  2. hibernate annotation注解方式来处理映射关系

    在hibernate中,通常配置对象关系映射关系有两种,一种是基于xml的方式,另一种是基于annotation的注解方式,熟话说,萝卜青菜,可有所爱,每个人都有自己喜欢的配置方式,我在试了这两种方式 ...

  3. 批量产生ssh2项目中hibernate带注解的pojo类的快捷方法

    近几个月一直在忙于项目组的ios应用项目的开发,没有太多时间去研究web应用方面的问题了.刚好,昨天有网友问到如何批量产生hibernate带注解的pojo类的快捷方法,所谓批量就是指将当前数据库中所 ...

  4. Hibernate基础学习(七)—检索方式

    一.概述      Hibernate有五种检索方式. 1.导航对象图检索方式      根据已经加载的对象,导航到其他对象. Order order = (Order)session.get(Ord ...

  5. Hibernate Annotations 注解

    Hibernate Annotations 注解 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么 ...

  6. Hibernate中用注解配置一对多双向关联和多对一单向关联

    Hibernate中用注解配置一对多双向关联和多对一单向关联 Hibernate提供了Hibernate Annotations扩展包,使用注解完成映射.在Hibernate3.3之前,需单独下载注解 ...

  7. Hibernate基于注解annotation的配置

    Annotation在框架中是越来越受欢迎了,因为annotation的配置比起XML的配置来说方便了很多,不需要大量的XML来书写,方便简单了很多,只要几个annotation的配置,就可以完成我们 ...

  8. Hibernate框架注解

    1.使用Hibernate注解的步骤                1.添加jar包                            Hibernate-annotations.jar      ...

  9. hibernate 常用注解

    转自:http://blog.csdn.net/numbibi/article/details/7739441 @content ejb3注解的API定义在javax.persistence.*包里面 ...

随机推荐

  1. android Button 属性

    Android中button 继承了TextView组件. 可以这么用: final TextView tv = new Button(getApplicationContext()); tv.set ...

  2. bzoj4540 序列 (单调栈+莫队+rmq)

    首先,如果我知道[l,r],要转移到[l,r+1]的时候,就是加上以r+1为右端点,[l,r+1]为左端点的区间的最小值,其他情况和这个类似 考虑这玩意怎么求 右端点固定的话,我左端点越往左走,这个最 ...

  3. Finding Lines UVALive - 6955(随机)

    给出n个点,问你有没有可能存在一条直线,这n个点中存在百分号p以上点在这条直线上. 两个点确定一条直线,所以可以随机枚举两个点,然后用这条直线去判断其他的点是不是在这条直线上,如果在这个直线上的点超过 ...

  4. 【mysql】mysql尾部空格

    mysql 字段为varchar类型的在查询时候胡忽略尾部空格. 先看表结构 插入一条数据包含空格 在查询是可以查到的 所有在插入数据的时候要对插入字段的数据处理下,php可以用函数trim()去掉两 ...

  5. NowCoder--牛客练习赛30 C_小K的疑惑

    题目链接 :牛客练习赛30 C_小K的疑惑 i j k 可以相同 而且 距离%2 只有 0 1两种情况 我们考虑 因为要 d(i j)=d(i k)=d(j k) 所以我们只能找 要么三个点 任意两个 ...

  6. mysql查看正在执行的sql语句

    有2个方法: 1.使用processlist,但是有个弊端,就是只能查看正在执行的sql语句,对应历史记录,查看不到.好处是不用设置,不会保存. -- use information_schema; ...

  7. (七)修改上一条SQL语句,NULL值的滤空函数nvl

    修改上一条SQL语句 1.用c命令来修改(c 即 change ) 默认,光标闪烁位置指向上一条SQL语句的第一行.输入二则定位到第二行. c /错误的关键字/正确的关键字 SQL form emp; ...

  8. Python之函数--命名空间、作用域、global、nonlocal、函数的嵌套和作用域链

    命名空间 -------‘’存放名字与值的关系”的空间 代码在运行伊始,创建的存储“变量名与值的关系”的空间叫做全局命名空间: 在函数的运行中开辟的临时的空间叫做局部命名空间. 命名空间一共分为三种: ...

  9. WebService的讲解 和 CXF 的初步使用

    1. 复习准备 1.1. Schema约束 几个重要知识: namespace 相当于schema文件的id targetNamespace属性 用来指定schema文件的namespace的值 xm ...

  10. pytest 6 生成html报告

    前言:pytest-HTML是一个插件,pytest用于生成测试结果的HTML报告.兼容Python 2.7,3.6 1.github上源码地址[https://github.com/pytest-d ...