hibernate的基础学习
工具类:
public class H3Util { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try {
//从类加载路径中读取hibernate.cfg.xml文件生成SessionFactory对象
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
基础的增删改查:
public class TestHibernate { @Test
public void add() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
for (int i = 0; i < 20; i++) {
session.save(new User(null, "test"+i, "123456", new Date(), 1, 1000.0f));
}
transaction.commit();
session.close();
System.out.println("成功");
} @Test
public void find() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("+++++++++");
User user = (User)session.get(User.class, 1);
System.out.println("======");
System.out.println(user);
session.close();
} @Test
public void del() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user = (User)session.get(User.class, 2);
session.delete(user);
transaction.commit();
session.close();
System.out.println("成功"+user);
} @Test
public void update() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user = (User)session.get(User.class, 1);
user.setPassword("111111");
session.update(user);
transaction.commit();
session.close();
System.out.println("成功"+user);
} @Test
public void findList() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
String hql = "from User";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<User> uList = query.list();
for (User user : uList) {
System.out.println(user);
}
session.close();
} }
测试hibernate的对象状态:
/**
* @author nunu
* 测试 hibernate 对象
*/
public class TestHibernateObject { /**
* 共有三种状态:
* 1、瞬时对象:TO 直接new对象
* 特点:
* 1、不受hibernate管理(session管理)
* 2、没有OID
* 2、持久化对象:PO
* 特点:
* 1、受hibernate管理(session管理)
* 2、有OID
* 3、离线(托管)对象:DO
* 特点:
* 1、曾经受过hibernate管理,现在不受管理的(session)
* 2、有OID
*/
@Test
public void status(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
Transaction ts = session.beginTransaction();
//user --> TO
User user = new User(null, "nnn", "1234568", new Date(), 0, 999.9f);
session.save(user);
ts.commit();
//session.close();
//user --> PO
System.out.println(user);
session.delete(user);
//user --> DO
System.out.println(user+"----");
} /**
* session 中数据发生更改,若事务提交,数据库中数据修改
* 若事务不提交,session关闭时,不会修改数据库
*/
@Test
public void addUser() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
Transaction ts = session.beginTransaction();
/**
* PO:持久化对象--数据库表中的记录同步的对象,只要该对象发生任何改变,session关闭时都会同步该对象的状态到数据库中的表记录上
User user = (User) session.get(User.class, "4028810d57c20db20157c20db5920013");
user.setUsername("wangwu");
*/ //DO
//User user = new User("4028408157c0f5920157c0f593e100001", "wangwu", "12312", new SimpleDateFormat("yyyy-MM-dd").parse("2016-10-14"), 1, 1000.0f);
//user.setUsername("wangwu"); //DO--PO :session -->一定会发生sql语句
//session.update(user); //PO
User user = (User) session.get(User.class, "4028810d57c20db20157c20db5920013"); //PO--TO
session.delete(user); /**
* 若不提交事务不会进行数据库修改
*/
ts.commit();
//session会拿session中的所有的持久化对象和
session.close(); System.out.println(user);
}
}
hibernate的一级缓存:
/**
* @author nunu
* 一级缓存
*/
public class TestHibernateSession { /**
* 查询结果会放入session中,从session中获取结果不需要查询语句
*/
@Test
public void sessionQuery() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession(); //默认所有查询,都会将结果存入到一级缓存(session)
//HQL、QBC、原生SQL查找:每次都会发送新sql,不会去session中获取
Query query = session.createQuery("from User where userId = '4028810d57c20db20157c20db58c000e'");
User user = (User)query.uniqueResult(); Query query1 = session.createQuery("from User where userId = 'ff80808157c72cbe0157c72cc1540000'");
User user1 = (User)query1.uniqueResult();
System.out.println("0"+user);
System.out.println("1"+user1);
User user2 = (User)session.get(User.class,"4028810d57c20db20157c20db58c000e");
//user2的获取不会发出查询语句
System.out.println("2"+user2);
session.close();
} /**
* 不发出update方法,修改session中结果是,再次获取的该值是修改过的结果
*
* 先去session缓存(一级缓存)查询看有没对应的对象
* 如果没有就会立即(无论有没有使用到该对象)发生sql语句去数据库查找,
* 查询到之后会将查询结果再存入到session缓存(一级缓存中)
*/
@Test
public void testSessionUpdate() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
User user = (User)session.get(User.class,"4028810d57c20db20157c20db5920013"); user.setUsername("admin"); //不会发送sql语句:
//User user1 = (User)session.get(User.class,"4028810d57c20db20157c20db5920013");
//System.out.println(user1);
//获取到是最新的对象信息
//System.out.println(user1.getUsername()); session.close();
} /**
* 懒加载
* org.hibernate.LazyInitializationException: could not initialize proxy - no Session
* 先去session缓存(一级缓存)查询看有没对应的对象
* 如果没有,再看程序中有没有使用改对象到除OID之外的属性,如果只是使用了OID它不会发送任何sql语句
* 但是如果使用除OID之外的属性,此时(使用之前)才会发送sql语句查询
*/
@Test
public void testLoad() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
User user1 = (User) session.load(User.class, "4028810d57c20db20157c20db5920013");
User user2 = (User) session.load(User.class, "ff80808157c72cbe0157c72cc1540000");
System.out.println("--------------"); System.out.println(user1);
System.out.println(user2); session.close(); //发送:sql
//System.out.println(user.getUsername()); //System.out.println(user1.getUsername());
}
}
hibernate的模糊查询、单条记录查询、分页查询、、等单表基本查询
public class TestQuery {
@Test
public void list() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
String hql = "from User";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<User> uList = query.list();
for (User user : uList) {
System.out.println(user);
}
session.close();
} /**
* 模糊查询
*/
@Test
public void list1() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
String hql = "from User as u where u.username like :username";
Query query = session.createQuery(hql);
query.setString("username", "%test1%");
@SuppressWarnings("unchecked")
List<User> uList = query.list();
for (User user : uList) {
System.out.println(user);
}
session.close();
} /**
* 模糊查询
*/
@Test
public void list2() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
String hql = "from User as u where u.username like ?";
Query query = session.createQuery(hql);
query.setString(0, "%test1%");
@SuppressWarnings("unchecked")
List<User> uList = query.list();
for (User user : uList) {
System.out.println(user);
}
session.close();
} /**
* 单个记录查询
*/
@Test
public void uniqueResult() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
String hql = "from User where userId = '4028810d57c20db20157c20db58c000a'";
Query query = session.createQuery(hql);
User u = (User) query.uniqueResult();
System.out.println(u);
session.close();
}
//findUsername
@Test
public void findUsername() {
SessionFactory sessionFactory = H3Util.getSessionFactory();
Session session = sessionFactory.openSession();
String hql = "select username from User";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<String> names = query.list();
for (String string : names) {
System.out.println("==="+string);
}
session.close();
} @Test//查询多个属性(投影)
public void findUsernameAndId(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession(); //sql:select username,sex from t_user
//String hql = "select sex,username from User where userId = '4028408157bbe02f0157bbe030820000' ";
//Query query = session.createQuery(hql); //返回值至多有一个:多了就会报异常 org.hibernate.NonUniqueResultException: query did not return a unique result: 2
/*Object[] obj = (Object[]) query.uniqueResult(); System.out.println("sex"+obj[0]);
System.out.println("username"+obj[1]);*/ //将查询结果封装到对象中:提供大量的构造方法
String hql = "select new User(userId,username) from User where userId = '4028810d57c20db20157c20db58b0005' ";
Query query = session.createQuery(hql);
User user = (User)query.uniqueResult(); System.out.println(user);
} /**
* 分页查询
*/
@Test
public void findByPage() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession(); int currentPage = 2;
int pageSize = 3;
String hql = "from User";
Query query = session.createQuery(hql);
query.setFirstResult((currentPage-1)*pageSize);
query.setMaxResults(pageSize);
@SuppressWarnings("unchecked")
List<User> uList = query.list();
for (User user : uList) {
System.out.println(user);
}
session.close();
} @Test//固定条件查询:查询username = 李四
public void findByUsername(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
String hql = "from User where username = '李四'";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<User> list = query.list();
for (User user : list) {
System.out.println(user);
}
}
@Test//可变参条件查询:查询username = 李四
public void findByUsername1(){
String username = "李四";
int sex = 1;
float salary = 10000.0f;
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//String hql = "from User where sex = ? and username = ? and salary = ?";
//Query query = session.createQuery(hql);
//为?设置具体数值
//只能使用索引方式设置值:此形式参数传递索引,灵活度太差,不推荐使用
//query.setString(0, username);
//query.setInteger(1, sex);
//query.setFloat(2, salary); //使用:别名 占位符形式
//使用属性名(占位符)方式设置值(推荐):名称和:后面的一致
String hql = "from User where sex = :sex and username = :username and salary = :salary";
Query query = session.createQuery(hql);
query.setString("username", username);
query.setInteger("sex", sex);
//query.setFloat("salary", salary);
query.setParameter("salary", salary);//如果不确定类型可以使用该方式,不推荐使用 @SuppressWarnings("unchecked")
List<User> list = query.list();
for (User user : list) {
System.out.println(user);
}
} @Test//统计记录个数
public void findCount(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
String hql = "select count(*) from User";
Query query = session.createQuery(hql); Long count = (Long) query.uniqueResult();
System.out.println(count);
} @Test//最小值
public void findMin(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//返回值:和字段类型一致
String hql = "select min(salary) from User";
Query query = session.createQuery(hql); Float min = (Float) query.uniqueResult();
System.out.println(min);
} @Test//求和
public void findSum(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//返回值:整形Long/小数Double
String hql = "select sum(salary) from User";
Query query = session.createQuery(hql); Double sum = (Double) query.uniqueResult();
System.out.println(sum);
}
@Test//求平均值
public void findAvg(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//返回值:Double
String hql = "select avg(salary) from User";
Query query = session.createQuery(hql); Double avg = (Double) query.uniqueResult();
System.out.println(avg);
} @Test//求分组查找
public void findGroup(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
String hql = "select sex, count(*) from User group by sex";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<Object[]> list = query.list();
for (int i=0;i<list.size();i++) {
System.out.println(list.get(i)[0]+":"+list.get(i)[1]);
}
}
@Test//求排序
public void findOrder(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
String hql = "from User order by salary asc,sex asc";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<User> list = query.list();
for (User user : list) {
System.out.println(user);
}
}
@Test//求排序
public void findOrder1(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
Query query = session.getNamedQuery("findOrder");
@SuppressWarnings("unchecked")
List<User> list = query.list();
for (User user : list) {
System.out.println(user);
}
}
}
hibernate的QBC:query by criteria
/**
* @author nunu
* QBC:query by criteria
*/
public class TestCriteria { /**
* criteria 普通查询
*/
@Test
public void list(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
Criteria criteria = session.createCriteria(User.class);
@SuppressWarnings("unchecked")
List<User> uList = criteria.list();
for (User user : uList) {
System.out.println(user);
}
} /**
* 查询用户名
*/
@Test
public void findUsername(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//select username from User
Criteria criteria = session.createCriteria(User.class);
//准备投影(属性)
Property prop = Property.forName("username");
//设置投影(属性)
criteria.setProjection(prop); @SuppressWarnings("unchecked")
List<String> usernames = criteria.list();
for (String name : usernames) {
System.out.println(name);
}
} /**
* 查询用户名和性别
*/
@Test
public void findUsernameSex(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//select username from User
Criteria criteria = session.createCriteria(User.class);
//准备投影(属性)
Property prop1 = Property.forName("username");
Property prop2 = Property.forName("sex"); //获取投影集合
ProjectionList pList = Projections.projectionList();
pList.add(prop1);
pList.add(prop2);
//设置投影(属性)
criteria.setProjection(pList); @SuppressWarnings("unchecked")
List<Object[]> usernames = criteria.list();
for (int i = 0; i < usernames.size(); i++) {
System.out.println(usernames.get(i)[0]+":"+usernames.get(i)[1]);;
}
} /**
* 模糊查询
*/
@Test
public void findByName(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//select username from User where username = :name
Criteria criteria = session.createCriteria(User.class);
//添加条件
//criteria.add(Restrictions.eq("username", "李四"));
criteria.add(Restrictions.like("username", "%test1%")); @SuppressWarnings("unchecked")
List<User> list = criteria.list();
for (User user : list) {
System.out.println(user);
}
}
@Test
public void findGroup(){
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
//select username from User group by sex
Criteria criteria = session.createCriteria(User.class); Projection p1 = Projections.groupProperty("sex");
Projection p2 = Projections.rowCount();//count(*) ProjectionList pList = Projections.projectionList();
pList.add(p1);
pList.add(p2);
//分组
criteria.setProjection(pList);
@SuppressWarnings("unchecked")
List<Object[]> list = criteria.list(); for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i)[0]+":"+list.get(i)[1]);
}
}
}
hibernate 中使用SQL语句查询
/**
* @author nunu
* hibernate 中使用SQL语句查询
*/
public class TestSQLQuery { @Test
public void testList() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
String sql = "select * from t_user";
SQLQuery sqlQuery = session.createSQLQuery(sql);
@SuppressWarnings("unchecked")
List<Object[]> uList = sqlQuery.list();
for (Object[] user : uList) {
for (int i = 0; i < user.length; i++) {
System.out.println(user[i]);
}
}
} @Test
public void testList1() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
String sql = "select * from t_user";
SQLQuery sqlQuery = session.createSQLQuery(sql);
//告诉系统如何去封装对象
sqlQuery.addEntity(User.class);
@SuppressWarnings("unchecked")
List<User> uList = sqlQuery.list();
for (User user : uList) {
System.out.println(user);
}
} /**
* 指明对象
*/
@Test
public void testList2() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
String sql = "select u.* from t_user u";
SQLQuery sqlQuery = session.createSQLQuery(sql);
//告诉系统如何去封装对象
sqlQuery.addEntity("u",User.class);
@SuppressWarnings("unchecked")
List<User> uList = sqlQuery.list();
for (User user : uList) {
System.out.println(user);
}
}
}
hibernate的基础学习的更多相关文章
- hibernate的基础学习--一对多关联
基本的用户和部门类,只有uuid和名称,没有其余字段. 配置文件 部门: <?xml version="1.0" encoding="utf-8" ?&g ...
- hibernate的基础学习--多表关联数据查询
Hibernate共提供4种多表关联数据查询方式 OID数据查询+OGN数据查询方式 HQL数据查询方式 QBC数据查询方式 本地SQL查询方式(hibernate很少用) 1.OID数据查询+OGN ...
- hibernate的基础学习--多对多关联
多对多采用学生老师模型进行测试 学生配置文件: <?xml version="1.0" encoding="utf-8" ?> <!DOCTY ...
- hibernate的基础学习--一对一关联
一对一关系以丈夫和妻子模型 配置文件 妻子配置文件: <?xml version="1.0" encoding="utf-8" ?> <!DO ...
- Hibernate基础学习2
Hibernate基础学习2 测试hibernate的一级缓存,事务以及查询语句 1)Hibernate的一些相关概念 hibernate的一级缓存 1)缓存是为了提高该框架对数据库的查询速度 2)一 ...
- Hibernate 马士兵 学习笔记 (转)
目录(?)[+] 第2课 Hibernate UML图 第3课 风格 第4课 资源 第5课 环境准备 第6课 第一个示例Hibernate HelloWorld 第7课 建立Annotation版本的 ...
- JAVA基础学习-集合三-Map、HashMap,TreeMap与常用API
森林森 一份耕耘,一份收获 博客园 首页 新随笔 联系 管理 订阅 随笔- 397 文章- 0 评论- 78 JAVA基础学习day16--集合三-Map.HashMap,TreeMap与常用A ...
- Spring Framework基础学习
Spring Framework基础学习 Core support for dependency injection,transaction management,web applications,d ...
- MacOS下SpringBoot基础学习
学于黑马和传智播客联合做的教学项目 感谢 黑马官网 传智播客官网 微信搜索"艺术行者",关注并回复关键词"springboot"获取视频和教程资料! b站在线视 ...
随机推荐
- Sentinel实现Redis高可用
实现目标: 一主两从,集群起始VIP在master上边,如果当前master挂了,sentinel自动选出一个slave当选master,并把VIP漂移到这台机器,然后把另一台slave指向的mast ...
- react 创建组件 (四)Stateless Functional Component
上面我们提到的创建组件的方式,都是用来创建包含状态和用户交互的复杂组件,当组件本身只是用来展示,所有数据都是通过props传入的时候,我们便可以使用Stateless Functional Compo ...
- vue 实现 扫二维码 功能
前段时间一直在研究,如何通过 vue 调用 相机 实现 扫一扫的功能,但是查看文档发现,需要获取 getUserMedia 的属性值,但存在兼容性问题. 退而求其次,通过 h5plus 来实现. 1. ...
- hdu 1250 Hat's Fibonacci
pid=1250">点击此处就可以传送hdu 1250 Problem Description A Fibonacci sequence is calculated by adding ...
- ruby rails
http://www.zhihu.com/question/19552402 作者:陈振宇链接:http://www.zhihu.com/question/19552402/answer/1236 ...
- 不能选择sublime作为默认打开方式的解决办法
Sublime Text 绿色版删除后无法设置为默认打开方式…而且网上也没有给出明确的解决办法 注册表的解决办法: 删除 HKEY_CURRENT_USER\Software\Classes\Appl ...
- Tomcat 80端口 配置及域名访问步骤
一.修改端口tomcat默认监听端口是8080,我们如果想不带端口的直接访问项目,就必须监听80 端口: service.xml 以下代码段 <Connector port="8080 ...
- Arcgis Engine(ae)接口详解(3):featureClass的feature编辑和删除
//由于测试数据不完善,featureClass在此要只设null值,真实功能要设实际的值 IFeatureClass featureClass = null; //获取某个字段的索引,后面取字段值用 ...
- ajax的异步操作及页面重定向跳转
今天主要分享一个简单的ajax的异步操作数据,用javascript也有一段时间了,刚开始看到一些页面在没有页面刷新的情况下就可以实现数据的保存或者获取,觉得挺不可思议的,感觉速度很快,做了几个项目之 ...
- sim的准确识别技术
几个月钱,我换了一个手机,本着工科男动手能力强的原则,自己用✂️把sim卡剪成了一个小卡,然后成功的可以使用了. 然而就在昨天,我将卡拿出之后,再放回去,却无法识别我的sim卡了. 我上网查了方法,怀 ...