Mybatis与Spring整合连接MySQL
Posted 楚兴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis与Spring整合连接MySQL相关的知识,希望对你有一定的参考价值。
1 maven依赖
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
2 数据库表
表名为student,位于test库中。
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
3 数据库表的映射类
package club.chuxing.tech.learn.mybatis.domain;
public class Student {
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
}
4 数据库访问DAO
package club.chuxing.tech.learn.mybatis.dao;
import club.chuxing.tech.learn.mybatis.domain.Student;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
@Component
public interface StudentDao {
@Select("select * from student where id = #{id}")
Student selectStudent(int id);
}
此DAO不需要对应的Mapper文件。
5 Mybatis配置文件
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>
<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="true"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings>
<!-- Continue going here -->
<typeAliases>
<typeAlias alias="Student" type="club.chuxing.tech.learn.mybatis.domain.Student" />
</typeAliases>
</configuration>
6 Spring配置文件
applicationContext-common.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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">
<context:annotation-config/>
<!--扫描包进行注入-->
<context:component-scan base-package="club.chuxing.tech.learn.mybatis.dao" />
<!--创建数据源dataSource对象并注入到SqlSessionFactoryBean对象中-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis.xml" />
<property name="mapperLocations">
<list>
<value>classpath:mybatis-mapper/*Mapper.xml</value>
</list>
</property>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"/>
</bean>
<!-- 配置扫描Mapper接口的包路径 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 如果是多个包名可用",; \t\n"中任意符号分隔开,详见:MapperScannerConfigurer[269行] -->
<property name="basePackage" value="club.chuxing.tech.learn.mybatis.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
7 DAO单元测试
package club.chuxing.tech.learn.mybatis.dao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import club.chuxing.tech.learn.mybatis.domain.Student;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static club.chuxing.tech.learn.utils.PrintUtil.*;
@ContextConfiguration(locations = "classpath:applicationContext-common.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentDaoTest {
@Autowired
private StudentDao dao;
@Test
public void testSelectStudent() throws Exception {
Student student = dao.selectStudent(1);
print(student);
}
}
也可以在Main函数中加载DAO bean:
package club.chuxing.tech.learn.mybatis;
import club.chuxing.tech.learn.mybatis.dao.StudentDao;
import club.chuxing.tech.learn.mybatis.domain.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static club.chuxing.tech.learn.utils.PrintUtil.print;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-common.xml");
StudentDao dao = context.getBean(StudentDao.class);
Student student = dao.selectStudent(1);
print(student);
}
}
以上是关于Mybatis与Spring整合连接MySQL的主要内容,如果未能解决你的问题,请参考以下文章
Spring+SpringMVC+Mybatis+Mysql整合实例