欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Maven + Spring 整合 Mybatis

程序员文章站 2022-04-23 15:45:14
...

运行环境:maven + spring4.0.0 + mybatis3.2.4 + mybatis-spring1.2.2


一、编辑pom.xml配置文件,添加依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.darren.framework.mybatis.mybatis-parent</groupId>
		<artifactId>mybatis-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<groupId>com.darren.framework.mybatis.mybatis-spring</groupId>
	<artifactId>mybatis-spring</artifactId>

	<!-- 说明:由于该工程是另外一个项目的子模块,所有版本的定义都在那个项目的pom.xml里面,所以如果要单独使用该文件,需添加对应的版本号 -->
	<dependencies>
		<!-- spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
		</dependency>

		<!-- mybatis spring支持 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
		</dependency>

		<!-- proxool -->
		<dependency>
			<groupId>com.cloudhopper.proxool</groupId>
			<artifactId>proxool</artifactId>
		</dependency>
		<dependency>
			<groupId>com.cloudhopper.proxool</groupId>
			<artifactId>proxool-cglib</artifactId>
		</dependency>
	</dependencies>

</project>

二、创建实体类:User

package com.darren.models;

import java.io.Serializable;

public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private int uid;
	private String userName;
	private String password;

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	@Override
	public String toString() {
		return "uId: "+this.uid + ", Name: " + this.userName + ",Pass: " + this.password;
	}
}

三、创建接口:UserDao

package com.darren.daointerface;

import java.util.List;

import com.darren.models.User;

public interface UserDao {

	public User queryById(int id);
	
	public void save(User u);
	
	public void update(User u);
	
	public void delete(Integer id);
	
	public List<User> queryAll();
}


四、接口实现类:

package com.darren.mybatis;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.darren.daointerface.UserDao;
import com.darren.models.User;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	
	@Override
	public User queryById(int id) {
		return (User) sqlSessionTemplate.selectOne("queryById", 3);
	}

	@Override
	public void save(User u) {
		sqlSessionTemplate.insert("insert-user", u);
	}

	@Override
	public void update(User u) {
		sqlSessionTemplate.update("update-user", u);
	}

	@Override
	public void delete(Integer id) {
		sqlSessionTemplate.delete("delete-user",id);
	}

	@Override
	public List<User> queryAll() {
		List<User> users = sqlSessionTemplate.selectList("queryAll");
		return users;
	}

}

说明:

1、@Repository:spring中的注解,把类注册到spring容器中.

2、@Autowired:由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"
	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-3.0.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx
     	   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
           	
	<!-- 采用注释的方式配置bean -->  
    <context:annotation-config />  
    <!-- 配置要扫描的包 -->  
    <context:component-scan base-package="com.darren"></context:component-scan>

	<!-- 加载 jdbc.properties 配置文件 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>

	<!-- 配置数据源(连接池,proxool) -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
		<property name="targetDataSource">
			<bean class="org.logicalcobwebs.proxool.ProxoolDataSource">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="driverUrl" value="${jdbc.url}" />
				<property name="user" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
				<property name="maximumConnectionCount" value="${proxool.maxConnCount}" />
				<property name="minimumConnectionCount" value="${proxool.minConnCount}" />
				<property name="statistics" value="${proxool.statistics}" />
				<property name="simultaneousBuildThrottle" value="${proxool.simultaneousBuildThrottle}" />
				<property name="trace" value="${proxool.trace}" />
			</bean>
		</property>
	</bean>

	<!-- Session工厂 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- mybatis配置文件 -->
		<property name="configLocation" value="classpath:mybatis.xml" />
	</bean>
	
	<!-- 配置SqlSessionTemplate -->  
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />  
    </bean>

</beans>  


六、添加jdbc.properties

proxool.maxConnCount=10
proxool.minConnCount=5
proxool.statistics=1m,15m,1h,1d
proxool.simultaneousBuildThrottle=30
proxool.trace=false
  
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

七、添加mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<typeAliases>
		<typeAlias alias="user" type="com.darren.models.User"/>
	</typeAliases>
	
	<!-- 指定映射文件 -->
	<mappers>
		<mapper resource="sqlmap/User-sqlmap-mapping.xml" />
	</mappers>
</configuration>


八、添加User-sqlmap-mapping.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  
<mapper namespace="com.darren.models.User">

	<cache />
	
	<resultMap type="User" id="resultListUser">
		<id column="uid" property="uid" />
		<result column="userName" property="userName"/>
		<result column="password" property="password" />
	</resultMap>
	
	<select id="queryById" resultType="User" parameterType="int">
		SELECT
		UID,
		USERNAME,
		PASSWORD
		FROM USERS
		WHERE UID = #{id}
	</select>
	
	<insert id="insert-user" parameterType="User" useGeneratedKeys="true" keyProperty="uid">
        	insert into
        	users(userName,password) values(#{userName},#{password}) 
	</insert>
	
	<update id="update-user" parameterType="User">
		UPDATE USERS SET USERNAME=#{userName},PASSWORD=#{password} WHERE UID=#{uid}
	</update>
	
	<delete id="delete-user" parameterType="int">
		DELETE USERS WHERE UID=#{id}
	</delete>
	
	<select id="queryAll" resultMap="resultListUser">
		SELECT * FROM USERS
	</select>
</mapper>

九、添加测试类:

package com.darren.user;

import java.util.List;

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.darren.models.User;
import com.darren.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/applicationContext.xml")
public class UserServiceTest {

	@Autowired
	UserService userService; 
	
	@Test
	public void testQueryById(){
		User u = userService.queryById(1);
		if(u != null){
			System.out.println(u);
		}
	}
	
	@Test
	public void testInsert() {
		for(int i = 0; i < 100; i++){
			User u = new User();
			u.setUserName("whh");
			u.setPassword("sb");
			userService.save(u);
		}
		System.out.println("保存成功!");
	}
	
	@Test
	public void testUpdate(){
		User u = userService.queryById(3);
		u.setUserName("scott");
		u.setPassword("scott");
		userService.update(u);
		System.out.println("修改成功!");
	}
	
	
	@Test
	public void testDelete(){
		int id = 4;
		userService.delete(id);
		
	}
	
	
	@Test
	public void testQueryAll(){
		List<User> users = userService.queryAll();
		if(users != null){
			for(int i = 0; i < users.size(); i++){
				System.out.println(users.get(i));
			}
		}
	}
}