今天来整合了一下spring,hibernate。
其实在前面S2sh框架整合的学习下,整合这个感觉还是比较轻松的,首先导入的jar包一下少了很多,因为springmvc本来就是spring框架的一部分,只需要将spring-webmvc跟spring-web(这个包之前好像也要加入进去)这些jar包导入进来,其他部分就是spring的一些其他的jar包跟hibernate的一些jar包,这些包的导入在这里就不描述了,可以在csdn上下载整个测试项目进行查看:http://download.youkuaiyun.com/detail/mjcreator/9526168
另外,在这里还是要说一下,在这个项目中commons-pool跟commons-dbcp这两个包还是不可以少的。
好了,jar包的导入在这里不继续记录了。
接下来帖上原代码以供以后参看吧。
web.xml文件的配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:component-scan base-package=" cn.bdx.controller, cn.bdx.dao.impl, cn.bdx.service.impl, cn.bdx.model" /> <!-- springmvc的配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 读取配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value> classpath:jdbc.properties </value> </list> </property> </bean> <!-- 配置数据库驱动 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>cn.bdx.model.User</value> </list> </property> <property name="hibernateProperties"> <props> <!-- 配置时前面最好添加上 'hibernate.' --> <!-- 一个Hibernate Dialect类名允许Hibernate针对特定的关系数据库生成优化的SQL --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- 输出所有SQL语句到控制台 --> <prop key="hibernate.show_sql">true</prop> <!-- 在log和console中打印出更漂亮的SQL --> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> </beans>
jdbc.properties文件的配置:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc\:mysql\://localhost\:3306/item?useUnicode\=true&characterEncoding\=utf-8&autoReconnect\=true jdbc.username=root jdbc.password=123456
好了,到这里配置文件差不多了。
User类:
package cn.bdx.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
UserController类的代码:
package cn.bdx.controller;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.bdx.model.User;
import cn.bdx.service.intf.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/add")
public ModelAndView add(User user,ModelMap model) {
this.userService.add(user);
System.out.println("add user complete");
return new ModelAndView("index",model);
}
@RequestMapping("/query")
public ModelAndView query(ModelMap model) {
this.userService.query();
System.out.println("query user compelte");
return new ModelAndView("index",model);
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
UserService接口的代码:
package cn.bdx.service.intf;
import java.util.List;
import cn.bdx.model.User;
public interface UserService {
public void add(User user);
public List<User> query();
}
UserServiceImpl类的代码:
package cn.bdx.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.bdx.dao.intf.UserDao;
import cn.bdx.model.User;
import cn.bdx.service.intf.UserService;
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource
private UserDao userDao;
@Override
public void add(User user) {
this.userDao.add(user);
}
@Override
public List<User> query() {
return this.userDao.query();
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
UserDao接口的代码:
package cn.bdx.dao.intf;
import java.util.List;
import cn.bdx.model.User;
public interface UserDao {
public void add(User user);
public List<User> query();
}
UserDaoImpl类的代码:
package cn.bdx.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import cn.bdx.dao.intf.UserDao;
import cn.bdx.model.User;
@Repository("userDao")
public class UserDaoImpl implements UserDao{
@Resource
private HibernateTemplate hibernateTemplate;
@Override
@Transactional(readOnly=false)
public void add(User user) {
this.hibernateTemplate.save(user);
}
@Override
public List<User> query() {
List<User> userList = (List<User>)this.hibernateTemplate.find("from User");
System.out.println(userList);
return userList;
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
好了到这里基本上的内容完毕了,接下来只需要部署并启动tomcat,访问http://localhost:8080/spring-hibernate-test/user/query或者http://localhost:8080/spring-hibernate-test/user/add进行测试即可。成功的话会跳转到index.jsp页面上去,并且在控制台有输出内容。
其实做这个项目我就是想看看一个事情,那就是我将springmvc-servlet.xml这个配置文件不要看看能不能行,事实证明是可以的,只是将需要修改几个地方。首先一个修改的地方就是web.xml文件中关于设置springmvc的servlet处:
如果需要springmvc-servlet.xml这个文件,配置的方式如下:注意"param-value"的值。
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:*-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
如果不需要这个文件,则需要指定一个其他的xml配置文件来完成springmvc的视图解析器bean的配置,我这里指定的是applicationContext.xml文件,这个web.xml文件关于springmvc的配置如下:注意其中的"param-value"的值。其实看这两个"param-value"的值不难看出,只是将对应xml文件的名称换了而已。
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
然后就是springmvc视图解析器bean的注入代码:
<!-- springmvc的配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean>