一、创建项目,准备jar包
项目结构二、配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置读取properties文件的工具类 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置c3p0数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver.class}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置Hibernate的SeesionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- hibernateProperties属性:配置与hibernate相关的内容,如显示sql语句,开启正向工程 -->
<property name="hibernateProperties">
<props>
<!-- 显示当前执行的sql语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 开启正向工程 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 扫描实体所在的包 -->
<property name="packagesToScan">
<list>
<value>com.tinner.pojo</value>
</list>
</property>
</bean>
<!-- 配置Hibernate的事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置HibernateTemplete对象-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置开启注解事务处理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置springIOC的注解扫描 -->
<context:component-scan base-package="com.tinner"/>
</beans>
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=050401
三、创建数据库、编写实体类
创建数据库就不说了,大家都会,这边直接粘贴实体类的代码
@Entity
@Table(name="t_users")
public class Users implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//strategy=GenerationType.IDENTITY 自增长
@Column(name="userid")
private Integer userid;
@Column(name="username")
private String username;
@Column(name="userage")
private Integer userage;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
}
四、编写UserDao接口与接口实现类
1.接口实现类
@Repository
public class UsersDaoImpl implements UsersDao {
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public void insertUsers(Users users) {
this.hibernateTemplate.save(users);
}
@Override
public void updateUsers(Users users) {
this.hibernateTemplate.update(users);
}
@Override
public void deleteUsers(Users users) {
this.hibernateTemplate.delete(users);
}
@Override
public Users selectUsersById(Integer userid) {
return this.hibernateTemplate.get(Users.class, userid);
}
}
2.测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserDaoImplTest {
@Autowired
private UserDao userDao;
/**
* 添加用户
*/
@Test
@Transactional// 在测试类对于事务提交方式默认的是回滚。
@Rollback(false)//取消自动回滚
public void testInsertUsers() {
Users user = new Users();
user.setUserage(20);
user.setUsername("张三");
this.userDao.insertUsers(user);
}
/**
* 更新用户
*/
@Test
@Transactional
@Rollback(false)
public void testUpdateUsers(){
Users users = new Users();
users.setUserid(2);
users.setUserage(22);
users.setUsername("李四");
this.userDao.updateUsers(users);
}
/**
* 根据userid查询用户
*/
@Test
public void testSelectUsersById(){
Users users = this.userDao.selectUserById(2);
System.out.println(users);
}
/**
* 删除用户
*/
@Test
@Transactional
@Rollback(false)
public void testDeleteUsers(){
Users users = new Users();
users.setUserid(2);
this.userDao.deleteUsers(users);
}
}
五、HQL查询
HQL:Hibernate Query Language
HQL的语法:就是将原来的sql语句中的表与字段名称换成对象与属性的名称就可以了
1.查询方法
这里注意:getCurrentSession:当前session必须要有事务边界,且只能处理唯一的一个事务。当事务提交或者回滚后session自动失效
openSession:每次都会打开一个新的session.假如每次使用多次。则获得的是不同session对象。使用完毕后我们需要手动的调用colse方法关闭session
@Override
public List<Users> selectUserByName(String userName) {
//getCurrentSession:当前session必须要有事务边界,且只能处理唯一的一个事务。当事务提交或者回滚后session自动失效
//openSession:每次都会打开一个新的session.假如每次使用多次。则获得的是不同session对象。使用完毕后我们需要手动的调用colse方法关闭session
Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
Query query = session.createQuery("from Users where username = :name").setString("name", userName);
return query.list();
}
2.测试代码
/**
* HQL测试
*/
@Test
@Transactional
public void testSelectUserByName(){
List<Users> list = this.userDao.selectUserByName("张三");
for (Users users : list) {
System.out.println(users);
}
}
六、SQL查询
1.查询方法
@Override
public List<Users> selectUserByNameUseSQL(String userName) {
Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
Query query = session.createSQLQuery("select * from t_users where username = ?").addEntity(Users.class).setString(0,userName );
// TODO Auto-generated method stub
return query.list();
}
2.测试代码
/**
* SQL测试
*/
@Test
@Transactional
public void testSelectUserByNameUseSQL(){
List<Users> list = this.userDao.selectUserByNameUseSQL("张三");
for (Users users : list) {
System.out.println(users);
}
}
七、QBC查询
QBC:Query By Criteria
彻底放弃掉关系型数据库的sql语句写法,全都换成以对象和方法的形式给替代
1.查询方法
@Override
public List<Users> selectUserByNameUseCriteria(String userName) {
Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
//sql:select * from t_users where username = 张三
Criteria criteria = session.createCriteria(Users.class);
//eq即相等
criteria.add(Restrictions.eq("username", userName));
return criteria.list();
}
2.测试代码
/**
* Criteria测试
*/
@Test
@Transactional
public void testSelectUserByNameUseCriteria(){
List<Users> list = this.userDao.selectUserByNameUseCriteria("张三");
for (Users users : list) {
System.out.println(users);
}
}
八、代码链接
相关代码已上传至github,链接:spring-data-hibernate
网友评论