说明
有没有小伙伴跟我一样,学过了就忘记了,之前学了hibernate以及Struts2框架,然后一直没有怎么用,后面很快就觉得不太会了。当然了,看到代码还是可以看懂的,但是让自己想就是有很多东西想不起来。这里主要就是hibernate框架整合,我跟着左慈老师的视频整合的。如果三个框架都学过的,整合起来其实不是特别困难,难的是在spring这一块。
主要是两步
1.spring整合hibernate
这里spring整合hibernate分成两种,一种是有hibernate.cfg.xml文件的,一种是没有hibernate.cfg.xml文件的
2.Struts2整合spring
这里也分成两种,一种是spring创建action,一种是structs2创建action
我们这里主要说一下spring整合hibernate,至于后续步骤,Struts2整合spring的可以看一下我的下一篇博客。
jar包
有一个很奇怪的事,就是我记得我之前整合jar包的时候没有用到这么多,这里居然要用到39个,(不过我后来查了一下,之前整的时候把spring中能放的包都放进去了,所以好像不止40个)而且有一些jar包还是我之前没有接触到的,但是这样导入也没有出错,所以应该也可以吧。如果有些小伙伴找不到jar包的话,可以去https://mvnrepository.com/找,这里的jar包挺多的。如果还不想一个个找,那你可以试试去https://how2j.cn/找一下,因为一般这里项目下面都会给出lib文件,下载下来,里面的jar包一般够用了,不够再去maven仓库找一下。
这里不一一介绍每个包是干嘛用的了,因为之前学的时候其实都有听过干嘛用的,但是除了一些记得住,有一些包确实是已经忘记干嘛用的了。但是spring的4+1,aop,jdbc,连接池,测试,web开发以及数据库的驱动这些包还是要知道的,其他的Struts2的核心包,hibernate的核心,日志,事务什么的。有一些我也记不清了。
准备工作
我们先在数据库中建一个表
create table t_user(
id int primary key auto_increment,
username varchar(50),
password varchar(32),
age int
);
把jar包和表建好了,基本准备工作就做完了。
建立User类,并与数据库表形成映射
首先根据t_user表写一个javabean
User.java
package com.shanmu.domain;
public class User {
private Integer id;
private String username;
private String pasword;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasword() {
return pasword;
}
public void setPasword(String pasword) {
this.pasword = pasword;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
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.shanmu.domain.User" table="t_user">
<!-- 配置主键 -->
<id name="id">
<generator class="native"></generator>
</id>
<property name="username"></property>
<property name="password"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
DAO层
分别有接口和实现类,都是简单的代码
package com.shanmu.dao;
import com.shanmu.domain.User;
public interface UserDao {
/**
* 保存
* @param user
*/
public void save(User user);
}
下面是实现类
package com.shanmu.dao.impl;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.shanmu.dao.UserDao;
import com.shanmu.domain.User;
public class UserDaoImpl implements UserDao{
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public void save(User user) {
this.hibernateTemplate.save(user);
}
}
service层
同样是接口和实现类
接口如下
package com.shanmu.service;
import com.shanmu.domain.User;
public interface UserService {
/**
* 注册
* @param user
*/
public void register(User user);
}
实现类如下
package com.shanmu.service.impl;
import com.shanmu.dao.UserDao;
import com.shanmu.domain.User;
import com.shanmu.service.UserService;
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void register(User user) {
userDao.save(user);
}
}
这里主要讲整合,所以没有特别注重实现功能,所以代码都比较简单,如果后面有做到实例的话,代码会比较难一点,不过应该不会做ssh的实例,因为更想做的是ssm的。
接下来就是写hibernate的配置文件还有spring的配置文件了。
首先,hibernate配置文件 hibernate.cfg.xml
现在也可以选择不用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>
<session-factory>
<!-- 数据库连接配置—基本四项 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/数据库名</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">密码</property>
<!-- 配置方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- sql语句 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 自动生成表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 本地线程绑定 -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 导入映射文件 -->
<mapping resource="com/shanmu/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
接下来是spring的配置文件
注意:spring这里有点麻烦
这里我们获得模板跟使用jdbcTemplate是不一样的,我们使用jdbcTemplate时需要的是DataSource,但是我们使用HibernateTemplate需要的确实SessionFactory。
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载hibernate.cfg.xml 获得SessionFactory -->
<bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 确定配置文件的位置 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 创建模板 -->
<bean name="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- dao -->
<bean name="userDao" class="com.shanmu.dao.impl.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!-- service -->
<bean name="userService" class="com.shanmu.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!-- 事务管理 -->
<!-- 事务管理器:HibernateTransactionManager -->
<bean name="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务详情 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="register"/>
</tx:attributes>
</tx:advice>
<!-- AOP编程 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.shanmu.service..*.*(..))"/>
</aop:config>
</beans>
下面可以写一个测试类测试一下spring整合hibernate成不成功
TestApp.java
package com.shanmu;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.shanmu.domain.User;
import com.shanmu.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestApp {
@Autowired
private UserService userService;
@Test
public void demo01(){
User user=new User();
user.setUsername("shanmu");
user.setPassword("1234");
user.setAge(18);
userService.register(user);
}
}
测试之后就能看到数据库多了一条数据
看看我们一直到现在的目录
上面说的是有hibernate.cfg.xml文件的,下面来看看如果不用hibernate.cfg.xml文件该怎么做。首先我们需要删除hibernate.cfg.xml文件,然后将原本的内容写入spring的配置文件中,然后修改我们的dao层,需要继承HibernateDaoSupport,看一下修改后的目录,主要修改applicationContext.xml以及UserDaoImpl.java,删除hibernate.cfg.xml文件,另外我把数据库的配置放入到jdbcInfo.properties,加入了log4j.properties文件(解决警告,可在hibernate包中找到该文件)。
修改后的UserDaoImpl.java
package com.shanmu.dao.impl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.shanmu.dao.UserDao;
import com.shanmu.domain.User;
//底层需要SessionFactory,自动创建HibernateTemplate模板
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
@Override
public void save(User user) {
this.getHibernateTemplate().save(user);
}
}
修改后的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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载properties文件 -->
<context:property-placeholder location="classpath:com/shanmu/jdbcInfo.properties"/>
<!-- 配置数据源 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${hibernate.driverClass}" ></property>
<property name="jdbcUrl" value="${hibernate.url}" ></property>
<property name="user" value="${hibernate.username}"></property>
<property name="password" value="${hibernate.password}" ></property>
</bean>
<!-- 配置hibernate.cfg.xml 获得SessionFactory -->
<bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 其他配置项 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
<!-- 导入配置文件 -->
<property name="mappingLocations" value="classpath:com/shanmu/domain/User.hbm.xml"></property>
<!-- 共4个mapping可以选择
加载执行映射文件,从src下开始,不支持通配符*
<property name="mappingResources" value="com/shanmu/domain/User.hbm.xml"></property>
确定映射文件位置,需要classpath,支持通配符
<property name="mappingLocations" value="classpath:com/shanmu/domain/User.hbm.xml"></property>
加载指定目录下的所有配置文件
<property name="mappingDirectoryLocations" value="classpath:com/shanmu/domain/"></property>
从jar包中获得映射文件
<property name="mappingJarLocations" ></property>
-->
</bean>
<!-- dao -->
<bean name="userDao" class="com.shanmu.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- service -->
<bean name="userService" class="com.shanmu.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!-- 事务管理 -->
<!-- 事务管理器:HibernateTransactionManager -->
<bean name="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务详情 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="register"/>
</tx:attributes>
</tx:advice>
<!-- AOP编程 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.shanmu.service..*.*(..))"/>
</aop:config>
</beans>
另外jdbcInfo.properties不会写,可以看一下
hibernate.driverClass=com.mysql.jdbc.Driver
hibernate.url=jdbc:mysql://localhost:3306/数据库名
hibernate.username=root
hibernate.password=密码
看一下最后运行的效果
这里没有改数据,所以导入的数据是一样的。另外这里测试了很多次,然后也把测试的数据删掉了,所以id已经增长到7了。
注意:数据库名和密码都要改成自己的数据库名和密码
最后
后面还会写一篇Struts整合spring的,两篇合起来才能完整整合。另外想尽快整合的话可以看一下how2java的教程,不过最好有基础看,不然只拿代码的话是看不懂的。