MyBatis与Spring整合

示例的目录结构:

MyBatis与Spring整合

1. 配置开发所需要的Jar包

本示例主要用到的Jar包主要有:

spring-4.0.6

mybatis-3.2.7

mybatis-spring-1.2.2

mysql-connector-java-5.1.22

junit-4.11


Jar包明细:

MyBatis与Spring整合


示例使用Maven管理Jar包,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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>lianliansteel</groupId>
  <artifactId>lianliansteel</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>lianliansteel</name>
  <url>http://maven.apache.org</url>
  <dependencies>
  	<!-- Spring 基础Jar包 : Begin -->
  	<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- Spring 基础Jar包 : End -->
    <!-- Spring JDBC 数据访问 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- Spring MVC 框架 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.7</version>
    </dependency>
    <!-- mybatis与spring的“粘合剂” -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- mysql driver -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.22</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <properties>
  	<org.springframework.version>4.0.6.RELEASE</org.springframework.version>
  </properties>
  <build>
    <finalName>lianliansteel</finalName>
  </build>
</project>

2. 在资源文件database.properties中配置数据库连接信息

database.driverClassName = com.mysql.jdbc.Driver
database.url = jdbc:mysql://127.0.0.1/SDGL?useUnicode=true&characterEncoding=utf8
database.username = root
database.password = abc123


3. 编写实例类及Dao类

Entity.java:

package com.sdgl.common;

import java.io.Serializable;

public interface Entity extends Serializable {

}


Department.java:

package com.sdgl.admin.entity;

import com.sdgl.common.Entity;

/**
 * 部门
 * @author wgc
 *
 */
public class Department implements Entity {

	private static final long serialVersionUID = -3212983578086635496L;

	private Long id = 0L;

	private String name = "";				//部门名称
	private String description = "";		//部门
	private String code = "";				//部门代码

	private Boolean disabled = false;		//是否可用
	private Long parentId = 0L;				//上级部门ID
	private Long creatorId = 0L;			//创建者ID
	private Long createTime = 0L;			//创建时间
	private Long lastAccess = 0L;			//最后更新时间
	
	public Department() {}
	
	public Department(String name, String description, Long parentId, Long creatorId, String code) {
		this.id = 0L;
		this.name = name;
		this.description = description;
		this.code = code.trim();
		this.disabled = false;
		this.parentId = parentId;
		this.creatorId = creatorId;
		this.createTime = System.currentTimeMillis();
		this.lastAccess = 0L;
	}

	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 String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Boolean getDisabled() {
		return disabled;
	}

	public void setDisabled(Boolean disabled) {
		this.disabled = disabled;
	}

	public Long getParentId() {
		return parentId;
	}

	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}

	public Long getCreatorId() {
		return creatorId;
	}

	public void setCreatorId(Long creatorId) {
		this.creatorId = creatorId;
	}

	public Long getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Long createTime) {
		this.createTime = createTime;
	}

	public Long getLastAccess() {
		return lastAccess;
	}

	public void setLastAccess(Long lastAccess) {
		this.lastAccess = lastAccess;
	}
	
}

DepartmentDao.java:

package com.sdgl.admin.dao;

import com.sdgl.admin.entity.Department;

public interface DepartmentDao {

	void save(Department department);
}


4. 添加MyBatis的Mapper文件 Department.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.sdgl.admin.dao.DepartmentDao">
  <insert id="save" parameterType="Department">
    INSERT INTO BAS_DEPARTMENT 
    	(name, description, code, disabled, parentId, creatorId, createTime, lastAccess) 
    VALUES 
    	(#{name}, #{description}, #{code}, #{disabled}, #{parentId}, #{creatorId}, #{createTime}, #{lastAccess})
    <selectKey resultType="long" keyProperty="id">
      SELECT last_insert_id() AS id FROM BAS_DEPARTMENT LIMIT 1
    </selectKey>
  </insert>
</mapper>

5. 注册Dao类

business-admin.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
	<bean id="departmentDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
	  <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	  <property name="mapperInterface" value="com.sdgl.admin.dao.DepartmentDao"></property>
	</bean>   
</beans>


6. 在Spring核心配置文件applicationContext.xml中配置数据源、MyBatis组件

<?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-3.0.xsd">
        
	<context:property-placeholder location="classpath:database.properties"/>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	  <property name="driverClassName" value="${database.driverClassName}"></property>
	  <property name="url" value="${database.url}"></property>
	  <property name="username" value="${database.username}"></property>
	  <property name="password" value="${database.password}"></property>
	</bean>
	
	<!-- 配置MyBatis组件:SqlSessionFactoryBean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	  <!-- 指定数据源 -->
	  <property name="dataSource" ref="dataSource"></property>
	  <!-- 指定mybatis的核心配置文件 -->
	  <property name="configLocation" value="classpath:mybatis-config.xml"></property>
	</bean>
	
	<!-- 导入资源文件 -->
	<import resource="com/sdgl/admin/service/business-admin.xml"></import>
</beans>


MyBatis核心配置文件

mybatis-config.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 type="com.sdgl.admin.entity.Department" alias="Department"/>
  </typeAliases>
  <mappers>
    <mapper resource="com/sdgl/admin/dao/Department.xml"/>
  </mappers>
</configuration>

7. 编写测试类

DepartmentDaoTest.java:

package com.sdgl.admin.dao;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sdgl.admin.entity.Department;

public class DepartmentDaoTest {

	@Test
	public void testSave() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		DepartmentDao dao = ctx.getBean("departmentDao", DepartmentDao.class);
		
		Department department = new Department("first", "mybatis与spring整合-测试", 0L, 0L, "01");
		
		dao.save(department);
	}
}

8. 验证

在数据库中查询记录是否已经成功插入



你可能感兴趣的:(mybatis)