搭建一个项目,不单单是MVC,我们还需要涉及到数据访问层,这里就需要hibernate框架来实现。(实现数据访问的框架很多,这里学习hibernate)
一、创建一个web项目
首先我们需要创建一个web项目,引入spring和hibernate的相关jar包,配置web.xml和spring和hibernate的配置文件,最后写入实体和方法就可以实现了。
二、引入jar包
下载地址:http://download.youkuaiyun.com/detail/w410589502/9738833
三、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring-core.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring-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>
<filter>
<filter-name>Spring OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBean</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Spring OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
四、spring的配置文件
1、spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<description>MVC配置文件 </description>
<!-- 激活组件扫描功能,自动扫描通过注解配置的组件 -->
<context:component-scan base-package="com.ssh.*"/>
<!-- 开启注解 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" p:supportedMediaTypes="text/html; charset=UTF-8" />
</mvc:message-converters>
</mvc:annotation-driven>
<context:annotation-config />
<!-- 开启AOP自动代理功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<!-- 视图解释器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Bean解析器,级别高于默认解析器,寻找bean对象进行二次处理 -->
<bean id="beanNameViewResolver"
class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0">
</bean>
<mvc:resources mapping="/js/**" location="/resources/js/"/>
</beans>
2、spring-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<description>持久层配置文件 </description>
<!-- 定义受环境影响易变的变量 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath*:datasource.properties</value>
</list>
</property>
</bean>
<!-- 配置c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="3"/>
<!--初始化时获取连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="5"/>
<property name="minPoolSize" value="3"/>
<property name="maxPoolSize" value="100"/>
<!--最大空闲时间,30秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="30"/>
<!--每30秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="30"/>
<property name="maxStatements" value="5000"/>
<property name="numHelperThreads" value="3"/>
</bean>
<!-- Annotation 配置sessionFactory,配置数据库连接,注入hibernate数据库配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ssh.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 链接释放策略 on_close | after_transaction | after_statement | auto -->
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<!--prop key="hibernate.hbm2ddl.auto">update</prop-->
</props>
</property>
<property name="namingStrategy" >
<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
</property>
</bean>
<!-- 事务管理器配置,单数据源事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务的传播特性 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="transactionAdvice" pointcut="execution(* com.ssh.biz..*.*(..))"/>
</aop:config>
</beans>
3、spring-core.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<import resource="spring-servlet.xml"/>
<import resource="spring-hibernate.xml"/>
</beans>
4、datasource.properties数据库配置文件
jdbc.url=jdbc\:mysql\://192.168.1.1\:3306/springHibernateTest?useUnicode\=true&characterEncoding\=utf-8
jdbc.username=admin
jdbc.password=admin123
hibernate.show_sql=true
hibernate.format_sql=false
五、实现类
1:entity实体类
package com.ssh.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "user_base_info" )
public class UserBaseInfo implements Serializable{
private static final long serialVersionUID = -1948330516997216009L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "status")
private Integer status;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Temporal(value = TemporalType.TIMESTAMP)
@Column(name = "create_time")
private Date createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
2:逻辑层
package com.ssh.biz.impl;
import java.util.List;
import com.ssh.entity.UserBaseInfo;
public interface UserBaseInfoBizImpl {
public List<UserBaseInfo> findUserBaseInfo();
}
package com.ssh.biz;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ssh.biz.impl.UserBaseInfoBizImpl;
import com.ssh.dao.impl.UserBaseInfoDaoImpl;
import com.ssh.entity.UserBaseInfo;
@Service("UserService")
public class UserBaseInfoBiz implements UserBaseInfoBizImpl{
@Resource(name = "UserBaseInfoDao")
private UserBaseInfoDaoImpl usesBaseInfoDao;
public List<UserBaseInfo> findUserBaseInfo(){
return usesBaseInfoDao.findUserBaseInfo();
}
}
3:数据访问层
package com.ssh.dao.impl;
import java.util.List;
import com.ssh.entity.UserBaseInfo;
public interface UserBaseInfoDaoImpl {
public List<UserBaseInfo> findUserBaseInfo();
}
package com.ssh.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.ssh.dao.impl.UserBaseInfoDaoImpl;
import com.ssh.entity.UserBaseInfo;
@Repository("UserBaseInfoDao")
public class UserBaseInfoDao implements UserBaseInfoDaoImpl{
@Autowired
protected SessionFactory sessionFactory;
protected JdbcTemplate jdbcTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<UserBaseInfo> findUserBaseInfo(){
/* String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list(); */
RowMapper<UserBaseInfo> rowMapper = new BeanPropertyRowMapper<UserBaseInfo>(UserBaseInfo.class);
String hql = "select id,name from user_base_info ";
return (List<UserBaseInfo>) this.jdbcTemplate.queryForObject(hql, rowMapper);
}
}
4:控制层
/**
*
* 类名称:SpringController
* 类描述:spring测试
* 创建人:wangql
* 创建时间:2017-1-12 上午10:01:43
* @version
*/
@Controller
@RequestMapping(value="/spring")
public class SpringController {
@Resource(name="UserService")
private UserBaseInfoBizImpl userBaseInfoBiz;
/**
* 方法名:测试方法
* 开发者:wangql
* 开发时间:2017-1-12
*/
@RequestMapping(value="/test",method = {RequestMethod.POST,RequestMethod.GET})
public String hello(){
return "/test";
}
@RequestMapping(value="/list",method = {RequestMethod.POST,RequestMethod.GET})
public void userList(){
List<UserBaseInfo> userBaseInfos = userBaseInfoBiz.findUserBaseInfo();
if(userBaseInfos != null){
for (UserBaseInfo userBaseInfo : userBaseInfos) {
System.out.println(userBaseInfo.getName());
}
}
}
}
访问:http://localhost:8080/SpringHibernateTest/spring/list
控制台输出user_base_info的name值