springmvc+spring4.1.6+hibernate4.3.8 integration annotation

Today, I will integrate spring and hibernate.

In fact, under the previous study of S2sh framework integration, it is relatively easy to integrate this feeling. First, the imported jar package is much less, because springmvc is originally a part of the spring framework, you only need to combine spring-webmvc with spring-web (this package It seems to be added before) These jar packages are imported, and the other parts are some other jar packages of spring and some jar packages of hibernate. The import of these packages will not be described here. You can download the entire test project on csdn. View : http://download.csdn.net/detail/mjcreator/9526168

In addition, I have to say here that the two packages commons-pool and commons-dbcp are still indispensable in this project.

Well, the import of the jar package will not continue to be recorded here.

Next post the original code for future reference.

Configuration of the web.xml file:

<?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 file:

<?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 configuration -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/" />
			<property name="suffix" value=".jsp" />
		</bean>						
        						
        <!-- read configuration file -->
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        	<property name="locations">
	        	<list>
	        		<value>
	        			classpath:jdbc.properties
	        		</value>
	        	</list>
        	</property>
        </bean>
        
        <!-- configure database driver-->
       	<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>
					<!-- It is best to add 'hibernate.' in front of the configuration -->
					<!-- A Hibernate Dialect class name that allows Hibernate to generate optimized SQL for a specific relational database -->
					<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
					<!-- Output all SQL statements to the console -->
					<prop key="hibernate.show_sql">true</prop>
					<!-- Print prettier SQL in log and console -->
					<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>

 Configuration of jdbc.properties file:

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

Well, the configuration file is almost here.

User class:

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;
	}
	
	
}

 Code for UserController class:

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;
	}
	
	
	
	
}

 Code for UserService interface:

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();

}

 Code of UserServiceImpl class:

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;
	}
	
	

}

 The code of the UserDao interface:

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();
}

 Code of UserDaoImpl class:

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;
	}
	
	

}

 Well, the basic content here is completed, then you only need to deploy and start tomcat, visit http://localhost:8080/spring-hibernate-test/user/query or http://localhost:8080/spring-hibernate -test/user/add to test. If successful, it will jump to the index.jsp page, and there will be output in the console.

In fact, I just want to see one thing when I do this project, that is, I don't want to see if the configuration file springmvc-servlet.xml can work. It turns out that it is possible, but I will need to modify a few places. The first modification is in the web.xml file about setting the springmvc servlet:

If you need the file springmvc-servlet.xml, the configuration is as follows: pay attention to the value of "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>

 If you don't need this file, you need to specify another xml configuration file to complete the configuration of springmvc's view resolver bean. I specify the applicationContext.xml file here. The configuration of springmvc in this web.xml file is as follows: Pay attention to the The value of "param-value" . In fact, it is not difficult to see the value of these two "param-value", just change the name of the corresponding xml file.

<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>

 Then there is the injection code of the springmvc view resolver bean:

<!-- springmvc configuration -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/" />
			<property name="suffix" value=".jsp" />
		</bean>		

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326608770&siteId=291194637