mybatis-spring整合mybatis
搭建环境
说明:
基于 maven 构建项目进行测试
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>com.shaoming</groupId>
<artifactId>spring-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
</project>
2.测试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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/yonghedb?useUnicode=true&serverTimezone=CST&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
<!--<?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">-->
<!--<!– MyBatis的全局配置文件 –>-->
<!--<configuration >-->
<!--</configuration>-->
测试 mybatis
package com.shaoming.test;
import com.shaoming.springmybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class TestMyBatis {
public static void main(String[] args) throws Exception {
// 1. 加载 MyBatis 配置文件,创建 SqlSessionFactory
// 注:在实际的应用中,SqlSessionFactory 应该是单例
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
// 2. 创建一个 SqlSession 实例,进行数据库操作
sqlSession = sqlSessionFactory.openSession();
//获取对应的mapper接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.selectAll().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
System.out.println("报错 ... ... ");
} finally {
sqlSession.close();
}
}
}
3.测试 spring
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="testJavaBean" class="com.shaoming.test.TestJavaBean">
<property name="id" value="1"></property>
<property name="name" value="zhangsan"></property>
</bean>
</beans>
测试获取 spring ioc 容器中的 javabean
测试的 java bean
package com.shaoming.test;
public class TestJavaBean {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestJavaBean{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
测试从 spring 容器中获取 javabean
package com.shaoming.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(ctx);
TestJavaBean testJavaBean = (TestJavaBean) ctx.getBean("testJavaBean");
System.out.println(testJavaBean);
System.out.println(testJavaBean.getId() + " --- " + testJavaBean.getName());
}
}
4.定义 mybatis 需要的类
测试sql语句
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 100307
Source Host : localhost:3306
Source Schema : yonghedb
Target Server Type : MySQL
Target Server Version : 100307
File Encoding : 65001
Date: 10/06/2022 17:00:09
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Id',
`name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户名',
`age` int(3) NOT NULL DEFAULT 0 COMMENT '年龄',
`address` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '地址',
`email` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '邮件',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '张三', 18, '北京', 'xxx@163.com');
INSERT INTO `user` VALUES (2, '李四', 19, '上海', 'xxx@163.com');
INSERT INTO `user` VALUES (6, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (9, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (10, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (11, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (12, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (13, 'lubu', 18, 'nanjing', '1025378286@qq.com');
SET FOREIGN_KEY_CHECKS = 1;
jdbc连接信息
jdbc.properties
文件定义在项目 resources 目录下
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/yonghedb?useUnicode=true&serverTimezone=CST&characterEncoding=utf-8
db.username=root
db.password=root
实体类
package com.shaoming.springmybatis.entity;
public class User {
private Long id;
private String name;
private Integer age;
private String address;
private String email;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
", email='" + email + '\'' +
'}';
}
}
mapper接口
package com.shaoming.springmybatis.mapper;
import com.shaoming.springmybatis.entity.User;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
User selectByPrimaryKey(Long id);
List<User> selectAll();
int updateByPrimaryKey(User record);
}
service 接口
package com.shaoming.springmybatis.service;
import com.shaoming.springmybatis.entity.User;
import java.util.List;
public interface UserService {
int deleteByPrimaryKey(Long id);
int insert(User record);
User selectByPrimaryKey(Long id);
List<User> selectAll();
int updateByPrimaryKey(User record);
}
service实现类
package com.shaoming.springmybatis.service;
import com.shaoming.springmybatis.entity.User;
import com.shaoming.springmybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int deleteByPrimaryKey(Long id) {
return userMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(User record) {
return userMapper.insert(record);
}
@Override
public User selectByPrimaryKey(Long id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
@Override
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
}
}
mapper.xml 文件
定义在 resource 资源目录下的 mapper 目录下
<?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.shaoming.springmybatis.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.shaoming.springmybatis.entity.User">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="address" jdbcType="VARCHAR" property="address" />
<result column="email" jdbcType="VARCHAR" property="email" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.shaoming.springmybatis.entity.User">
insert into user (id, name, age,
address, email)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{address,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="com.shaoming.springmybatis.entity.User">
update user
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
address = #{address,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select id, name, age, address, email
from user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select id, name, age, address, email
from user
</select>
</mapper>
配置
mybatis-config.xml
说明:
mybatis 配置交给 spring 管理 , 我们只需要在 spring 配置文件中配置 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">
<!-- MyBatis的全局配置文件 -->
<configuration >
</configuration>
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--加载perperties配置文件的信息-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--加载druid资源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${db.driverClassName}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--spring整合mybatis后控制的创建连接用的对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
<property name="typeAliasesPackage" value="com.shaoming.springmybatis.entity"/>
</bean>
<!--加载mybatis映射配置的扫描,将其作为spring的bean进行管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.shaoming.springmybatis.mapper"/>
</bean>
<context:component-scan
base-package="com.shaoming.springmybatis">
</context:component-scan>
</beans>
测试
package com.shaoming.springmybatis;
import com.shaoming.springmybatis.mapper.UserMapper;
import com.shaoming.springmybatis.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SprinigMybatisTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Object dataSource = ac.getBean("dataSource");
System.out.println(dataSource);
System.out.println("mapper接口查询的结果");
UserMapper userMapper = (UserMapper) ac.getBean("userMapper");
userMapper.selectAll().forEach(System.out::println);
System.out.println("service接口查询的结果");
UserService userService = (UserService) ac.getBean("userServiceImpl");
userService.selectAll().forEach(System.out::println);
}
}
bug解决
测试类
UserService userService = (UserService) ac.getBean("userService");
具体报错
NoSuchBeanDefinitionException 异常
Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘userService’ available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:771)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
at com.shaoming.springmybatis.SprinigMybatisTest.main(SprinigMybatisTest.java:21)
debug 看 容器中的 bean 的名字
解决
方案一
UserService userService = (UserService) ac.getBean("userServiceImpl");
方案二
修改 @Service 注解, 指定 java bean 的名称
@Service("myService")
public class UserServiceImpl implements UserService {
....
}
UserService userService = (UserService) ac.getBean("myService");
=======
mybatis-spring整合mybatis
搭建环境
说明:
基于 maven 构建项目进行测试
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>com.shaoming</groupId>
<artifactId>spring-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
</project>
2.测试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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/yonghedb?useUnicode=true&serverTimezone=CST&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
<!--<?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">-->
<!--<!– MyBatis的全局配置文件 –>-->
<!--<configuration >-->
<!--</configuration>-->
测试 mybatis
package com.shaoming.test;
import com.shaoming.springmybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class TestMyBatis {
public static void main(String[] args) throws Exception {
// 1. 加载 MyBatis 配置文件,创建 SqlSessionFactory
// 注:在实际的应用中,SqlSessionFactory 应该是单例
SqlSession sqlSession = null;
InputStream inputStream = null;
try {
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
// 2. 创建一个 SqlSession 实例,进行数据库操作
sqlSession = sqlSessionFactory.openSession();
//获取对应的mapper接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.selectAll().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
System.out.println("报错 ... ... ");
} finally {
sqlSession.close();
}
}
}
3.测试 spring
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="testJavaBean" class="com.shaoming.test.TestJavaBean">
<property name="id" value="1"></property>
<property name="name" value="zhangsan"></property>
</bean>
</beans>
测试获取 spring ioc 容器中的 javabean
测试的 java bean
package com.shaoming.test;
public class TestJavaBean {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestJavaBean{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
测试从 spring 容器中获取 javabean
package com.shaoming.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(ctx);
TestJavaBean testJavaBean = (TestJavaBean) ctx.getBean("testJavaBean");
System.out.println(testJavaBean);
System.out.println(testJavaBean.getId() + " --- " + testJavaBean.getName());
}
}
4.定义 mybatis 需要的类
测试sql语句
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 100307
Source Host : localhost:3306
Source Schema : yonghedb
Target Server Type : MySQL
Target Server Version : 100307
File Encoding : 65001
Date: 10/06/2022 17:00:09
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Id',
`name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户名',
`age` int(3) NOT NULL DEFAULT 0 COMMENT '年龄',
`address` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '地址',
`email` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '邮件',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '张三', 18, '北京', 'xxx@163.com');
INSERT INTO `user` VALUES (2, '李四', 19, '上海', 'xxx@163.com');
INSERT INTO `user` VALUES (6, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (9, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (10, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (11, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (12, 'lubu', 18, 'nanjing', '1025378286@qq.com');
INSERT INTO `user` VALUES (13, 'lubu', 18, 'nanjing', '1025378286@qq.com');
SET FOREIGN_KEY_CHECKS = 1;
jdbc连接信息
jdbc.properties
文件定义在项目 resources 目录下
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/yonghedb?useUnicode=true&serverTimezone=CST&characterEncoding=utf-8
db.username=root
db.password=root
实体类
package com.shaoming.springmybatis.entity;
public class User {
private Long id;
private String name;
private Integer age;
private String address;
private String email;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
", email='" + email + '\'' +
'}';
}
}
mapper接口
package com.shaoming.springmybatis.mapper;
import com.shaoming.springmybatis.entity.User;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
User selectByPrimaryKey(Long id);
List<User> selectAll();
int updateByPrimaryKey(User record);
}
service 接口
package com.shaoming.springmybatis.service;
import com.shaoming.springmybatis.entity.User;
import java.util.List;
public interface UserService {
int deleteByPrimaryKey(Long id);
int insert(User record);
User selectByPrimaryKey(Long id);
List<User> selectAll();
int updateByPrimaryKey(User record);
}
service实现类
package com.shaoming.springmybatis.service;
import com.shaoming.springmybatis.entity.User;
import com.shaoming.springmybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int deleteByPrimaryKey(Long id) {
return userMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(User record) {
return userMapper.insert(record);
}
@Override
public User selectByPrimaryKey(Long id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
@Override
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
}
}
mapper.xml 文件
定义在 resource 资源目录下的 mapper 目录下
<?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.shaoming.springmybatis.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.shaoming.springmybatis.entity.User">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="address" jdbcType="VARCHAR" property="address" />
<result column="email" jdbcType="VARCHAR" property="email" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.shaoming.springmybatis.entity.User">
insert into user (id, name, age,
address, email)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{address,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="com.shaoming.springmybatis.entity.User">
update user
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
address = #{address,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select id, name, age, address, email
from user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select id, name, age, address, email
from user
</select>
</mapper>
配置
mybatis-config.xml
说明:
mybatis 配置交给 spring 管理 , 我们只需要在 spring 配置文件中配置 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">
<!-- MyBatis的全局配置文件 -->
<configuration >
</configuration>
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--加载perperties配置文件的信息-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--加载druid资源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${db.driverClassName}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--spring整合mybatis后控制的创建连接用的对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
<property name="typeAliasesPackage" value="com.shaoming.springmybatis.entity"/>
</bean>
<!--加载mybatis映射配置的扫描,将其作为spring的bean进行管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.shaoming.springmybatis.mapper"/>
</bean>
<context:component-scan
base-package="com.shaoming.springmybatis">
</context:component-scan>
</beans>
测试
package com.shaoming.springmybatis;
import com.shaoming.springmybatis.mapper.UserMapper;
import com.shaoming.springmybatis.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SprinigMybatisTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Object dataSource = ac.getBean("dataSource");
System.out.println(dataSource);
System.out.println("mapper接口查询的结果");
UserMapper userMapper = (UserMapper) ac.getBean("userMapper");
userMapper.selectAll().forEach(System.out::println);
System.out.println("service接口查询的结果");
UserService userService = (UserService) ac.getBean("userServiceImpl");
userService.selectAll().forEach(System.out::println);
}
}
bug解决
测试类
UserService userService = (UserService) ac.getBean("userService");
具体报错
NoSuchBeanDefinitionException 异常
Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘userService’ available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:771)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
at com.shaoming.springmybatis.SprinigMybatisTest.main(SprinigMybatisTest.java:21)
debug 看 容器中的 bean 的名字
解决
方案一
UserService userService = (UserService) ac.getBean("userServiceImpl");
方案二
修改 @Service 注解, 指定 java bean 的名称
@Service("myService")
public class UserServiceImpl implements UserService {
....
}
UserService userService = (UserService) ac.getBean("myService");
827f72e0ebce6d9f12a5f0aa66db7ea1b124e93e