1.Hibernate初步了解
(1)什么是hibernate,hibernate是用来做什么的
半成品的项目
hibernate是一个操作数据库的框架,实现了对JDBC的封装。
2.使用c3p0与dbutils编写用户注册功能
-
所需jar包如下
-
所建包结构如下:
-
webconten目录如下:
-
主要代码如下
userdao层:
package com.dao; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import com.domain.User; import com.yl.lain.utils.C3p0DataSourceUtils; public class UserDao { public void addUser(User user) throws SQLException { QueryRunner runner=new QueryRunner(C3p0DataSourceUtils.getDataSource()); String sql="insert into user2 values(?,?,?,?,?,?)"; runner.update(sql,user.getId(),user.getUsername(),user.getPassword(),user.getName(),user.getEmail(),user.getTelephone()); } }
c3p0xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/world?useSSL=false</property> <property name="user">root</property> <property name="password">root</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> <named-config name="oracel"> <property name="driverClass">oracle.jdbc.driver.OracleDriver</property> <property name="jdbcUrl">jdbc:oracle:thin:@//192.168.40.128/orcl</property> <property name="user">scott</property> <property name="password">scott</property> </named-config> </c3p0-config>
domain:
package com.domain; public class User { private String id; private String username; private String password; private String name; private String email; private String telephone; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } }
service:
package com.service; import java.sql.SQLException; import com.dao.UserDao; import com.domain.User; public class UserService { public void addUser(User user) throws SQLException { UserDao userDao=new UserDao(); userDao.addUser(user); } }
web:
package com.web; import java.util.UUID; import com.domain.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.service.UserService; public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user=new User(); public String register() throws Exception { //封装user //没有的我们手动封装 user.setId(UUID.randomUUID().toString()); //传递数据 UserService userService=new UserService(); userService.addUser(user); return "tologin"; } @Override public User getModel() { return user; } }
struts:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true"></constant> <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <package name="forum" namespace="/" extends="struts-default"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="UserAction_*" class="com.web.UserAction" method="register"> <result name="tologin" type="redirect">/login.html</result> </action> </package> </struts>
3.使用hibernate编写用户注册功能
搭建hibernate
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="hibernate" namespace="/" extends="struts-default"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="UserAction_*" class="com.web.UserAction" method="{1}"> <result name="tologin" type="redirect">/login.html</result> </action> </package> </struts>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="hibernate" namespace="/" extends="struts-default"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="UserAction_*" class="com.web.UserAction" method="{1}"> <result name="tologin" type="redirect">/login.html</result> </action> </package> </struts>
dao层:
package com.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.domain.User; public class UserDao { public void addUser(User user) { //使用hibernate //得到配置信息 Configuration config=new Configuration().configure(); //创建sessionfactory对象 SessionFactory sessionFactory = config.buildSessionFactory(); //获取session Session session = sessionFactory.openSession(); //打开事务 Transaction transaction = session.beginTransaction(); //存储user对象 session.save(user); //提交事务 transaction.commit(); //关闭资源 session.close(); } }
domain层:
user
package com.domain; public class User { private String id; private String username; private String password; private String name; private String email; private String telephone; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", name=" + name + ", email=" + email + ", telephone=" + telephone + "]"; } }
user.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.domain.User" table="user2"> <id name="id" column="id"> <!-- 主键生成策略 (手动生成)--> <generator class="assigned"></generator> </id> <property name="username" column="username"></property> <property name="password" column="password"></property> <property name="name" column="name"></property> <property name="email" column="email"></property> <property name="telephone" column="telephone"></property> </class> </hibernate-mapping>
service层:
package com.service; import com.dao.UserDao; import com.domain.User; public class UserService { public void addUser(User user) { UserDao dao=new UserDao(); dao.addUser(user); } }
web层:
userAction.java
package com.web; import java.util.UUID; import com.domain.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.service.UserService; public class UserAction extends ActionSupport implements ModelDriven<User>{ User user=new User(); public String register() throws Exception { user.setId(UUID.randomUUID().toString()); UserService userService=new UserService(); userService.addUser(user); return "tologin"; } @Override public User getModel() { // TODO Auto-generated method stub return user; } }
4.对比这两种方式
创建:
hibernate:
创建hibernate。cfg.xml
配置驱动,数据url,用户名,密码
数据库的方言
c3p0+dbutils:
c3p0:连接数据库
配置驱动,数据库url,用户名,密码
dbutils:操作数据库
添加实体:
hibernate:
需要实体与表的映射文件xxx.hbm.xml
需要配置属性与字段的对应,添加逐渐生成策略
c3p0+dbutils:
需要实体
操作数据库:
hibernate:
通过session来操作数据库(开启事务)
如何操作MySQL中的表:
不用写sql语句(hibernate帮你写),而且一行代码解决session.save();
原始的c3p0+dbutils:
通过queryrunner来操作数据库
如何操作MySQL中的表:
写sql语句,相对比与hibernate会比较麻烦,insert into user values(?,?,?,?......)
5.学习hibernate(重点)
(1)hibernate配置文件的讲解
- 配置数据库方言:
打开hibernate-core.final.jar
找到
若想hibernate自动生成表,要配置成如下的方言
- create: 自动创建表,每次框架运行都会创建一张新的表,原来的数据将丢失(开发)
- create-drop: 自动建表,每次框架运行结束都会删除所有的表(开发环境中测试使用)
- update(推荐): 自动生成表,如果表已经存在,则更新数据,添加数据,如果表不存在,就会创建一张新的表。
- validate:
- 配置mapping映射文件
- 格式化hibernate生成的sql语句
- 配置事务的隔离级别
- 配置事务
从而得到同一个session
- 其他配置
hibernate.cnf.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"> <hibernate-configuration> <!-- 负责初始化hibernate --> <session-factory> <!-- 连接数据库的驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库地址 --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world?useSSL=false</property> <!-- 数据库用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库密码 --> <property name="hibernate.connection.password">root</property> <!-- 配置数据库的方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 将hibernate生成的sql语句打印到控制台 --> <property name="hibernate.show_sql">true</property> <!-- 格式化hibernate生成的sql语句 --> <property name="hibernate.format.sql">true</property> <!-- hibernate自动创建表 create: 自动创建表,每次框架运行都会创建一张新的表,原来的数据将丢失(开发) create-drop: 自动建表,每次框架运行结束都会删除所有的表(开发环境中测试使用) update(推荐): 自动生成表,如果表已经存在,则更新数据,添加数据,如果表不存在,就会创建一张新的表。 validate: --> <property name="hibernate.hbm2ddl.auto">create</property> <!-- 映射文件配置 --> <mapping resource="com/domain/User.hbm.xml"/> </session-factory> </hibernate-configuration>
实体映射配置文件的讲解xxx.hbm.xml
-
主键生成策略5种
- identity:主键自增
- sequence:oracle中主键生成策略
- native:identity+sequence(hibernate会根据连接的数据库自动选择(identity,sequence))
- uuid:产生随机字符串作为主键,主键必须为String
- assigned:我们要手动去指定
若是手动生成,还需在action中设置id为字符串格式
- id元素
- 其他元素
user.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.domain"> <class name="User" table="user2"> <!-- id元素 name:实体中的属性 colum(可选):数据库的列名(一样的话可以不用配置) type(可选属性):填写列(属性)的类型.hibernate会自动检测实体的属性类型。每个类型有三种 填法:java类型|hibernate类型|数据库类型 length(可选):配置数据库中列的长度,默认值:使用数据库类型的最大长度。 --> <id name="id" column="id"> <!-- identity:主键自增 sequence:oracle中主键生成策略 native:identity+sequence(hibernate会根据连接的数据库自动选择(identity,sequence)) uuid:产生随机字符串作为主键,主键必须为String assigned:我们要手动去指定 --> <!-- 主键生成策略 (手动生成) --> <generator class="uuid"></generator> </id> <!-- property:除了id之外的普通属性 name:实体中的属性 colum(可选):数据库的列名 length(可选):配置数据库中列的长度 默认值:使用数据库类型的最大长度 not-null(可选):配置该属性是否不能为空,默认值false --> <property name="username" column="username"></property> <property name="password" column="password"></property> <property name="name" column="name"></property> <property name="email" column="email"></property> <property name="telephone" column="telephone"></property> </class> </hibernate-mapping>
(2)api的讲解
dao层:
1.Configuration
创建Configuration对象,并未读取-----》通过对象调用configure()方法读取配置文件信息。
configure是怎么读取的,相关源码如下:
2.SessionFactory
功能:创建session(数据库核心对象)的工厂。简单来说就是创建session对象。
sessionfactory 负责保存和使用所有配置信息消耗内存资源很大。
线程安全的。
3.Session(重点)
package com.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.domain.User; public class UserDao { public void addUser(User user) { //使用hibernate(并没有读取hibernate.cfg.xml) Configuration config1=new Configuration(); //读取配置文件 config1.configure(); //得到sessionfactory 功能:创建session(数据库核心对象)的工厂 // 简单来说就是创建session对象。 //sessionfactory 负责保存和使用所有配置信息消耗内存资源很大。 // 线程安全的。 SessionFactory factory = config1.buildSessionFactory(); //创建session对象 Session openSession=factory.openSession(); //得到配置信息 Configuration config=new Configuration().configure(); //创建sessionfactory对象 SessionFactory sessionFactory = config.buildSessionFactory(); //获取session Session session = sessionFactory.openSession(); //打开事务 Transaction transaction = session.beginTransaction(); //存储user对象 session.save(user); //提交事务 transaction.commit(); //关闭资源 session.close(); } public void deleteUser(){ Configuration config=new Configuration().configure(); SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); Transaction beginTransaction=session.beginTransaction(); //得到id为的对象 User user = session.get(User.class, "402881606adf5c93016adf5caacd0001"); session.delete(user); beginTransaction.commit(); session.close(); } public void ChangeUser(){ //读取hibernate.cfg.xml Configuration configuration=new Configuration().configure(); SessionFactory factory = configuration.buildSessionFactory(); Session session = factory.openSession(); Transaction beginTransaction = session.beginTransaction(); //获得id为402881606adf5c93016adf5caacd0001的对象。 User user = session.get(User.class, "402881606adf5c93016adf5caacd0001"); //将该对象改名为trigger user.setUsername("trigger"); //跟新数据库 session.update(user); //提交事务 beginTransaction.commit(); //关闭session session.close(); } public void findUser(){ Configuration config=new Configuration().configure(); SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); Transaction beginTransaction = session.beginTransaction(); User user =session.get(User.class, "402881606adf5c93016adf5caacd0001"); System.out.println(user.getName()); beginTransaction.commit(); session.close(); } }
(3)创建实体
- 提供无参的构造器
- 成员变量的私有化,提供getset方法,提供属性
- 尽量使用包装类
- 主键(实体要提供一个主键,与数据库中的列进行对应)
- 不要加final(hibernate 中使用代理机制)
(4)对象的三种状态
瞬时状态(transient)
实体 没有id,没有和session关联(hibernate中的session)
持久化状态(persistent) 特点:持久化状态的任何改变都会同步到数据库中
实体 有id,与session关联
游离态(detached 托管态)
实体,有id,没有与session关联
dao:
三种状态的转换
(5)一级缓存
dao
(6)事务管理
-
事务的性质
1.原子性:原子,不可再分,一个操作不能分为更小的操作,要么全都执行,要么全不执行。
2.一致性:事务在完成时,必须使得所有的数据保持一致的状态。(与开始事务前一样的状态)
3.隔离性:事务查看数据时数据所处的状态,要么是另一个并发事务修改它之前的状态,
要么是另一个并发事务修改后的状态,事务不会查看中间装态的数据。
4.持久性:事务操作之后,他对于系统的影响是永久性的。(执行了就执行了,没有撤回(反悔)的说法)
破坏了数据库。
-
事务的隔离级别
脏读:读取了未提交事务中的数据
不可重复读:对于数据库中的某个数据,一个事务范围内多次读取同一个数据,结果却有不同的值。
a事务第一读取值为100,b事务抢占资源,把值改为200。b事务结束。a事务接着读,值为两百。
幻读:对于多个事务操作数据库。a把数据库中的值修改了,b又改了,b事务结束了。a事务抢占了资源,发现值不对,以为产生了幻觉
不可重复读和幻读的区别:
http://www.cnblogs.com/itcomputer/articles/5133254.html
-
配置事务的隔离级别
1读未提交:最低的隔离级别,最没用(最快) 1(0001)
2读已提交:可避免脏读,不能避免不可重复读 2(0010)
3可重复读:可以避免可重复读,可以避免脏读(mysql默认) 4(0100)
4串行化:最强大,三种都可以解决。(最慢) 8(1000)
在hibernate.cfg.xml中:
-
使用事务小案例
点击按钮,根据id查找user--->找到user的名字改变
----->没找到,不做任何变化.
使一个服务为一个事务。
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"> <hibernate-configuration> <!-- 负责初始化hibernate --> <session-factory> <!-- 连接数据库的驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库地址 --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world?useSSL=false</property> <!-- 数据库用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库密码 --> <property name="hibernate.connection.password">root</property> <!-- 配置数据库的方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 将hibernate生成的sql语句打印到控制台 --> <property name="hibernate.show_sql">true</property> <!-- 格式化hibernate生成的sql语句 --> <property name="hibernate.format.sql">true</property> <!-- hibernate自动创建表 create: 自动创建表,每次框架运行都会创建一张新的表,原来的数据将丢失(开发) create-drop: 自动建表,每次框架运行结束都会删除所有的表(开发环境中测试使用) update(推荐): 自动生成表,如果表已经存在,则更新数据,添加数据,如果表不存在,就会创建一张新的表。 validate: --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 1(0001)读未提交:最低的隔离级别,最没用(最快) 2(0010)读已提交:可避免脏读,不能避免不可重复读 4(0100)可重复读:可以避免可重复读,可以避免脏读(mysql默认) 8(1000)串行化:最强大,三种都可以解决。(最慢) --> <property name="hibernate.connection.isolation">4</property> <!-- 配置事务 (session与当前线程绑定)--> <property name="hibernate.current_session_context_class">thread</property> <!-- 映射文件配置 --> <mapping resource="com/domain/User.hbm.xml"/> </session-factory> </hibernate-configuration>
struts.xml如下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="hibernate" namespace="/" extends="struts-default"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="UserAction_*" class="com.web.UserAction" method="{1}"> <result name="tologin" type="redirect">/login.html</result> </action> </package> </struts>
web层:
package com.web; import java.util.UUID; import com.domain.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.service.UserService; public class UserAction extends ActionSupport implements ModelDriven<User>{ User user=new User(); public String register() throws Exception { //user.setId(UUID.randomUUID().toString()); UserService userService=new UserService(); userService.addUser(user); return "tologin"; } public User getModel() { // TODO Auto-generated method stub return user; } }
service层
package com.service; import org.hibernate.Session; import org.hibernate.Transaction; import com.dao.UserDao; import com.domain.User; import com.utils.HibernateUtils; public class UserService { public void addUser(User user) { UserDao dao=new UserDao(); //开启事务 Session currentSession = HibernateUtils.getCurrentSession(); Transaction beginTransaction = currentSession.beginTransaction(); try{ //根据查找tuser //dao.addUser(); User tuser=dao.findUserById("1"); if(tuser!=null){ //如果找到了,根据id修改名字 dao.ChangeUserByUserId(tuser.getId()); } else{ } }catch(Exception e){ e.printStackTrace(); //事务的回滚 beginTransaction.rollback(); } //提交事务 beginTransaction.commit(); } }
dao层
package com.dao; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.domain.User; import com.utils.HibernateUtils; public class UserDao { public void addUser(/*User user*/) { /*//使用hibernate(并没有读取hibernate.cfg.xml) Configuration config1=new Configuration(); //读取配置文件 config1.configure(); //得到sessionfactory 功能:创建session(数据库核心对象)的工厂 // 简单来说就是创建session对象。 //sessionfactory 负责保存和使用所有配置信息消耗内存资源很大。 // 线程安全的。 SessionFactory factory = config1.buildSessionFactory(); //创建session对象 Session openSession=factory.openSession();*/ Session session = HibernateUtils.getSession(); Transaction transaction = session.beginTransaction(); User user=new User(); //=>瞬时状态 user.setName("lain");//=>瞬时状态 //存储user对象 只是为了生成id session.save(user); //有id,与session关联 持久化状态 本质:对象状态的转换 //将瞬时--->持久 目的:生成id //提交事务 transaction.commit(); //关闭资源 session.close(); //没有与session关联,有id。 } public void deleteUser(){ Configuration config=new Configuration().configure(); SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); Transaction beginTransaction=session.beginTransaction(); //得到id为的对象 User user = session.get(User.class, "402881606adf5c93016adf5caacd0001"); session.delete(user); beginTransaction.commit(); session.close(); } public void ChangeUser(){ //读取hibernate.cfg.xml Configuration configuration=new Configuration().configure(); SessionFactory factory = configuration.buildSessionFactory(); Session session = factory.openSession(); Transaction beginTransaction = session.beginTransaction(); //获得id为402881606adf5c93016adf5caacd0001的对象。 User user = session.get(User.class, "402881606adf5c93016adf5caacd0001"); User user1 = session.get(User.class, "1"); User user2 = session.get(User.class, "1"); System.out.println(user1==user2); //将该对象改名为trigger user.setUsername("trigger"); //跟新数据库 session.update(user); //提交事务 beginTransaction.commit(); //关闭session session.close(); } public void findUser(){ Configuration config=new Configuration().configure(); SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); Transaction beginTransaction = session.beginTransaction(); User user =session.get(User.class, "402881606adf5c93016adf5caacd0001"); System.out.println(user.getName()); beginTransaction.commit(); session.close(); } public User findUserById(String id) { Session session=HibernateUtils.getCurrentSession(); return session.get(User.class, id); } public void ChangeUserByUserId(String id) { // TODO Auto-generated method stub Session session=HibernateUtils.getCurrentSession(); //先拿到持久化user User user=session.get(User.class,id); //改变user(从持久态--->beginTransaction.commit()他才会同步到数据库) user.setUsername("trigger"); } }
domain层:
package com.domain; public class User { private String id; private String username; private String password; private String name; private String email; private String telephone; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", name=" + name + ", email=" + email + ", telephone=" + telephone + "]"; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.domain"> <class name="User" table="user2"> <!-- id元素 name:实体中的属性 colum(可选):数据库的列名(一样的话可以不用配置) type(可选属性):填写列(属性)的类型.hibernate会自动检测实体的属性类型。每个类型有三种 填法:java类型|hibernate类型|数据库类型 length(可选):配置数据库中列的长度,默认值:使用数据库类型的最大长度。 --> <id name="id" column="id"> <!-- identity:主键自增 sequence:oracle中主键生成策略 native:identity+sequence(hibernate会根据连接的数据库自动选择(identity,sequence)) uuid:产生随机字符串作为主键,主键必须为String assigned:我们要手动去指定 --> <!-- 主键生成策略 (手动生成) --> <generator class="uuid"></generator> </id> <!-- property:除了id之外的普通属性 name:实体中的属性 colum(可选):数据库的列名 length(可选):配置数据库中列的长度 默认值:使用数据库类型的最大长度 not-null(可选):配置该属性是否不能为空,默认值false --> <property name="username" column="username"></property> <property name="password" column="password"></property> <property name="name" column="name"></property> <property name="email" column="email"></property> <property name="telephone" column="telephone"></property> </class> </hibernate-mapping>
utils层
package com.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static SessionFactory sessionFactory=null; static{ //读取hibernate.cfg.xml Configuration config=new Configuration().configure(); //获取sessionFactory工厂 sessionFactory = config.buildSessionFactory(); } //获得全新得session public static Session getSession(){ //获取session Session session = sessionFactory.openSession(); return session; } // public static Session getCurrentSession(){ return sessionFactory.getCurrentSession(); } }
(7)HQL与Criteria与SQL
HQL
- 基本查询
package com.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; import com.domain.User; import com.utils.HibernateUtils; public class HQLDao { //测试基本查询 public void serach(){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////////////// //操作select * from user String hql="from com.domain.User"; Query query = session.createQuery(hql); List<User> list = query.list();//查询多条数据 //User user = (User)query.uniqueResult();//查询唯一的数据 System.out.println(list); /////////////////////////////////////// beginTransaction.commit(); session.close(); } }
package com.service; import org.hibernate.Session; import org.hibernate.Transaction; import com.dao.HQLDao; import com.dao.UserDao; import com.domain.User; import com.utils.HibernateUtils; public class UserService { public void test(){ HQLDao dao=new HQLDao(); dao.serach(); } public void addUser(User user) { UserDao dao=new UserDao(); //开启事务 Session currentSession = HibernateUtils.getCurrentSession(); Transaction beginTransaction = currentSession.beginTransaction(); try{ //根据查找tuser //dao.addUser(); User tuser=dao.findUserById("1"); if(tuser!=null){ //如果找到了,根据id修改名字 dao.ChangeUserByUserId(tuser.getId()); } else{ } }catch(Exception e){ e.printStackTrace(); //事务的回滚 beginTransaction.rollback(); } //提交事务 beginTransaction.commit(); } }
package com.web; import java.util.UUID; import com.domain.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.service.UserService; public class UserAction extends ActionSupport implements ModelDriven<User>{ User user=new User(); public String register() throws Exception { //user.setId(UUID.randomUUID().toString()); UserService userService=new UserService(); userService.test(); return "tologin"; } public User getModel() { // TODO Auto-generated method stub return user; } }
- 条件查询
- 基本条件查询
String hql="from com.domain.User where id=?0";
query.setParameter(0, id);
?占位符
String hql="from com.domain.User where id=?0";
- 命名占位符
String hql="from com.domain.User where id=:id";
/ /设置参数
query.setParameter("id", id);
- 分页查询
limit ?,?
String hql="from user com.domain.User";
query.setFirstResult(0);
query.setMaxResults(1);
package com.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; import com.domain.User; import com.utils.HibernateUtils; public class HQLDao { //测试基本查询 public void serach(){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////////////// //操作select * from user String hql="from com.domain.User"; Query query = session.createQuery(hql); List<User> list = query.list();//查询多条数据 //User user = (User)query.uniqueResult();//查询唯一的数据 System.out.println(list); /////////////////////////////////////// beginTransaction.commit(); session.close(); } //条件查询 public void serach1(){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////////////// //操作select * from user where id=1; String hql="from com.domain.User where id=1"; Query query = session.createQuery(hql); User user = (User)query.uniqueResult(); System.out.println(user); /////////////////////////////////////// beginTransaction.commit(); session.close(); } //条件查询 public void serach2(String id){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////////////// //操作select * from user where id=? user对象的id //sql语言完全面向对象的 String hql="from com.domain.User where id=?0"; Query query = session.createQuery(hql); //设置参数 query.setParameter(0, id); //query.setString(0, id); User user =(User) query.uniqueResult(); System.out.println(user.getPassword()); /////////////////////////////////////// beginTransaction.commit(); session.close(); } //命名占位符查询 public void serach3(String id){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////////////// //操作select * from user where id=? user对象的id //sql语言完全面向对象的 String hql="from com.domain.User where id=:id"; Query query=session.createQuery(hql); //设置参数 query.setParameter("id", id); User user=(User)query.uniqueResult(); System.out.println(user.getEmail()); /////////////////////////////////////// beginTransaction.commit(); session.close(); } //命名占位符查询 public void serach4(){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////////////// //操作select * from user limit 0,1; user对象的id //hql语言完全面向对象的 String hql="from user com.domain.User"; Query query = session.createQuery(hql); query.setFirstResult(0); query.setMaxResults(1); List<User> list = query.list(); System.out.println(list.get(0).getUsername()); /////////////////////////////////////// beginTransaction.commit(); session.close(); } }
Criteria
基本查询
条件查询
分页查询
查询总记录
package com.sikiedu.dao; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.Criteria; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.query.NativeQuery; import org.hibernate.query.Query; import com.sikiedu.domain.User; import com.sikiedu.utils.HibernateUtils; public class CriteriaDao { // 基本查询 public void search() { Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////// // 操作 select * from user CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); // createQuery-->查询条件(首先要知道查询什么类型数据) CriteriaQuery<User> createQuery = criteriaBuilder.createQuery(User.class); Root<User> from = createQuery.from(User.class); createQuery.select(from); // 执行查询 List<User> resultList = session.createQuery(createQuery).getResultList(); System.out.println(resultList); ///////////////////// beginTransaction.commit(); session.close(); } // 条件查询 public void search2() { Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////// // 操作 select * from user CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); // createQuery-->查询条件(首先要知道查询什么类型数据) CriteriaQuery<User> criteria = criteriaBuilder.createQuery(User.class); Root<User> root = criteria.from(User.class); criteria.select(root).where(root.get("id").in("1")); // 执行查询 List<User> resultList = session.createQuery(criteria).getResultList(); System.out.println(resultList); ///////////////////// beginTransaction.commit(); session.close(); } // 查询总数查询 public void search3() { Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////// // 操作 select count(*) from user CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); // createQuery-->查询条件(首先要知道查询什么类型数据)(数Integer Long) CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class); Root<User> root = criteria.from(User.class); criteria.select(criteriaBuilder.count(root)); // 执行查询 Long count = session.createQuery(criteria).uniqueResult(); System.out.println(count); ///////////////////// beginTransaction.commit(); session.close(); } //查询名字带有i的人的总数 -- 2 // 查询总数查询 public void search4() { Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); ///////////////////// // 操作 select count(*) from user where username like '%i%' CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class); Root<User> root = criteria.from(User.class); criteria.select(criteriaBuilder.count(root)).where(criteriaBuilder.like(root.get("username"), "%i%")); Long count = session.createQuery(criteria).uniqueResult(); System.out.println(count); ///////////////////// beginTransaction.commit(); session.close(); } }
sql
基本查询
条件查询
分页查询
package com.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.NativeQuery; import org.hibernate.query.Query; import com.domain.User; import com.utils.HibernateUtils; public class SQLDao { //sql基本查询 public void fun(){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); /////////////////////////////////////// String sql="select * from user2"; //创建sql查询 NativeQuery query = session.createSQLQuery(sql); //封装数据1 query.addEntity(User.class); //接收list List<User> list=query.list(); //接收单一返回值 //query.uniqueResult(); System.out.println(list.get(0).getUsername()+"---"+list.get(1).getUsername()+"--"+list.get(2).getUsername()); /////////////////////////////////////////// beginTransaction.commit(); session.close(); } //sql条件查询 public void fun2(){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); /////////////////////////////////////// String sql="select * from user where id= ?"; NativeQuery query = session.createSQLQuery(sql); //给?赋值 //从1开始 query.setParameter(1, 3); query.addEntity(User.class); User user = (User)query.uniqueResult(); System.out.println(user); /////////////////////////////////////////// beginTransaction.commit(); session.close(); } //sql分页查询 public void fun3(){ Session session = HibernateUtils.getSession(); Transaction beginTransaction = session.beginTransaction(); /////////////////////////////////////// String sql="select * from user limit ?,?"; NativeQuery query = session.createSQLQuery(sql); //给?赋值 //从1开始 query.setParameter(1, 0); query.setParameter(2, 2); query.addEntity(User.class); List<User> list = query.list(); System.out.println(list+"---"+list.get(0).getUsername()+"---"+list.get(1).getUsername()); /////////////////////////////////////////// beginTransaction.commit(); session.close(); } }
(8)一对多/多对一
(9)多对多