javaee之Spring的整合

原创 2016年08月30日 00:47:33
使用Spring来对JDBC进行整合


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


	<!-- 创建c3p0连接池 -->
	<bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/day35"></property>
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="user" value="root"></property>
		<property name="password" value="123"></property>
	</bean>
	
	<!-- 使用spring里面的jdbc工具 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dateSource"></property>
	</bean>
	
	<bean id="userdao" class="demo1_jdbc.UserDao" >
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
	
</beans>

User:
public class User {


	private int id;
	private String name;
	private String gender;
	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 String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", gender=" + gender + "]";
	}
	
	
	
}


UserDao:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;


public class UserDao {


	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	//添加的方法
	public void save(User user){
		jdbcTemplate.update("insert into t_user(id,name,gender) values (?,?,?)",user.getId(),user.getName(),user.getGender() );
	}
	
	//修改的方法
	public void update(User user){
		jdbcTemplate.update("update t_user set name=?,gender=? where id=?",user.getName(),user.getGender(),user.getId());
	}
	
	//删除的方法
	public void delete(int id){
		jdbcTemplate.update("delete from t_user where id=?",id);
	}
	
	//查询 所有的方法
	public List<User> findAll(){
		return jdbcTemplate.query("select * from t_user", new RowMapper(){


			@Override
			public Object mapRow(ResultSet rs, int arg1) throws SQLException {
				// TODO Auto-generated method stub
				User u = new User();
				u.setId(rs.getInt("id"));
				u.setName(rs.getString("name"));
				u.setGender(rs.getString("gender"));
				return u;
			}
			
		});
	}
	
	//查询一个用户
	public User findone(int id){
		 return jdbcTemplate.queryForObject("select * from t_user where id=?", new RowMapper(){


			@Override
			public Object mapRow(ResultSet rs, int arg1) throws SQLException {
				User u = new User();
				u.setId(rs.getInt("id"));
				u.setName(rs.getString("name"));
				u.setGender(rs.getString("gender"));
				return u;
				
			}
			
		},id);
	}
	
	//分页查询
	public List<User> findByPage(int curPage,int pageSize){
		 return jdbcTemplate.query("select * from t_user limit ?,?", new RowMapper(){


				@Override
				public Object mapRow(ResultSet rs, int arg1) throws SQLException {
					User u = new User();
					u.setId(rs.getInt("id"));
					u.setName(rs.getString("name"));
					u.setGender(rs.getString("gender"));
					return u;
					
				}
				
			},curPage,pageSize);
		}
	
	//查询总记录数
	public int findCount(){
		return jdbcTemplate.queryForObject("select count(*) from t_user", Long.class).intValue();
	}
}

测试类:
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class text {


	@Test
	public void test01(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDao userdao = (UserDao)ac.getBean("userdao");
		User u = new User();
		u.setId(3);
		u.setName("王五");
		u.setGender("男");
		userdao.save(u);
		
	}
	
	@Test
	public void test02(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDao userdao = (UserDao)ac.getBean("userdao");
		User u = new User();
		u.setId(2);
		u.setName("李四");
		u.setGender("女");
		userdao.update(u);
		
	}
	
	@Test
	public void test03(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDao userdao = (UserDao)ac.getBean("userdao");
		userdao.delete(2);
		
	}
	
	@Test
	public void test04(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDao userdao = (UserDao)ac.getBean("userdao");
		System.out.println(userdao.findAll());
		
	}
	
	@Test
	public void test05(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDao userdao = (UserDao)ac.getBean("userdao");
		System.out.println(userdao.findone(2));
		
	}
	
	@Test
	public void test06(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDao userdao = (UserDao)ac.getBean("userdao");
		System.out.println(userdao.findByPage(1, 2));
	}
	
	@Test
	public void test07(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDao userdao = (UserDao)ac.getBean("userdao");
		System.out.println(userdao.findCount());
	}
}


Spring整合Hibernate,使用HibernateTemplate工具来进行一些功能


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: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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd
        ">


	<!-- 创建c3p0连接池 -->
	<bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/day35"></property>
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="user" value="root"></property>
		<property name="password" value="123"></property>
	</bean>
	
	
	
	
	
	<!-- 先创建sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dateSource"></property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
		<property name="mappingResources">
			<list>
				<value>demo2_hibernate/Student.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id="studentdao" class="demo2_hibernate.StudentDao">
		<property name="hibernateTemplate" ref="hibernateTemplate"></property>
	</bean>
</beans>




Student:
public class Student {


	private int id;
	private String name;
	private String gender;
	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 String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", gender=" + gender
				+ "]";
	}
	
	
	
}


Student.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">




<hibernate-mapping  package="demo2_hibernate">
	
	<class name="Student"  table="t_student">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name" />
		<property name="gender" />
		
	</class>
</hibernate-mapping>

StudentDao:
import java.util.List;


import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;


public class StudentDao {


	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}


	public List<Student> findAll(){
		return hibernateTemplate.loadAll(Student.class);
		//return (List<Student>) hibernateTemplate.find("from Student");
	}
	
	public Student findById(int id){
		return hibernateTemplate.get(Student.class, id);
	}
	
	public List<Student> findByPage(final int curpage,final int pagesize){
		return hibernateTemplate.execute(new HibernateCallback<List<Student>>() {


			@Override
			public List<Student> doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
				Query query = session.createQuery("from Student");
				query.setFirstResult(curpage);
				query.setMaxResults(pagesize);
				return query.list();
			}
		});
	}
	
	public int findCount(){
		return hibernateTemplate.execute(new HibernateCallback<Long>() {


			@Override
			public Long doInHibernate(Session session) throws HibernateException {


				Query query = session.createQuery("select count(*) from Student");	
				
				return (Long) query.uniqueResult();
			}
		}).intValue();
	}
	
	//添加操作需要事务管理并且还需要aop
	public void save(Student student){
		hibernateTemplate.save(student);
	}
}


测试类:
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;




public class Text {


	@Test
	public void test01(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao dao = (StudentDao) ac.getBean("studentdao");
		System.out.println(dao.findAll());
	}
	
	@Test
	public void test02(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao dao = (StudentDao) ac.getBean("studentdao");
		System.out.println(dao.findById(2));
	}
	
	@Test
	public void test03(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao dao = (StudentDao) ac.getBean("studentdao");
		System.out.println(dao.findByPage(1, 2));
		
	}
	
	@Test
	public void test04(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao dao = (StudentDao) ac.getBean("studentdao");
		System.out.println(dao.findCount());
	}
	
	@Test
	public void test05(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao dao = (StudentDao) ac.getBean("studentdao");
		Student student = new Student();
		student.setName("张三");
		student.setGender("男");
		dao.save(student);
	}
}


使用Spring来整合Struts2,除了在applicationContext.xml要配置action外,还需要在web.xml的文件中定义Spring的核心监听器
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"
    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">
	
	<!-- 1.创建service业务对象 -->
	<bean id="userServiceID" class="gz.itcast.service.UserServiceImpl"></bean>
	
	<!-- 2.整合的关键点: 在spring中创建struts2用到的Action对象 -->
	<!-- scope="prototype":action对象必须是多例的,否则会出现线程并发问题 -->
	<bean id="userActionID" class="gz.itcast.web.UserAction" scope="prototype">
		<!-- 注入service对象 -->
		<property name="userService" ref="userServiceID"/>
	</bean>
	
</beans>


struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">


<struts>


	<package name="base" extends="struts-default" namespace="/">
		<!-- userActionID:代表spring创建出来的一个Action对象 -->
		<action name="user_*" class="userActionID" method="{1}">
			<result>/succ.jsp</result>
		</action>
	</package>


</struts>


User:
public class User {
	private String name;
	private String gender;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", gender=" + gender + ", age=" + age
				+ "]";
	}
	
}


UserService:
public class UserServiceImpl implements IUserService {


	public void save(User user) {
		System.out.println("进入业务方法:保存用户:"+user);
	}


}



UserAction:

import com.opensymphony.xwork2.ActionSupport;


public class UserAction extends ActionSupport{
	//接收一个业务逻辑对象
	private IUserService userService;
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}




	//接收参数
	private User user;
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}




	//注册方法
	public String reg(){
		System.out.println("进入了注册方法");
		System.out.println(user);
		
		//调用业务逻辑
		userService.save(user);
		
		return SUCCESS;
	}
}


web.xml:
<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocaltion</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	<context-param>



学习完Spring来用整合Struts2和hibernate,那么以后就可以通过三大框架来进行开发项目了

博为峰JavaEE技术文章 ——MyBatis Spring 整合-MapperScannerConfigurer

SSH框架现在应用非常广泛,一般的中小项目,大多都会使用Spring和MyBatis。两者结合轻便好使,易上手。今天小博老师给大家介绍Spring和Mybatis结合的方式之一,使用MapperSca...
  • bwf_erg
  • bwf_erg
  • 2017年03月07日 18:29
  • 81

JavaEE SSH框架整合(四) 日志处理Spring结合 log4j、slf4j

1. 加入log4j和slf4j的jar包 2. web.xml:   log4jConfigLocation /WEB-INF/classes/log4j.properties --> ...

Spring boot学习(一)创建JavaEE初始化项目

创建初始化项目 下一步:选择需要关联的子项目,此时初始化的是一个web项目,因此选择对应的web、devtools、jpa、MySQL等四个插件 DevTools:使用这个的目的主要是用于...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:javaee之Spring的整合
举报原因:
原因补充:

(最多只允许输入30个字)