mybatis与spring的整合
程序员文章站
2022-06-17 16:15:50
...
整合思路
1、准备jar包
(1)spring的jar包
(2)mybatis的jar包
(3)spring+mybatis的jar包
(4)数据库驱动jar包
(5)数据库连接池jar包
2、创建工程
创建一个普通的java project 工程
3、导入准备的所有jar包
4、创建config文件夹(注意选择source folder)
(1)创建配置文件SqlMApConfig.xml文件,jdbc.properties,log4j.properties.
SqlMapConfig.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>
<!-- 指定扫描包,会把包内所有的类设置别名,别名的名称就是类名,大小写不敏感 -->
<package name="com.project.mybatis.pojo"/>
</typeAliases>
<mappers>
<mapper resource="mybatis/User.xml"/>
</mappers>
</configuration>
jdbc,properties配置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_spring?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
log4j.properties配置
# Global logging configuration
log4j.rootLogger=debug, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
(2)创建applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置 读取properties文件 jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置 数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"><!-- com.alibaba.druid.pool.DruidDataSource -->
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 数据库最大连接数 -->
<property name="maxActive" value="10"/>
<!-- 最大空闲数 -->
<property name="maxIdle" value="5"/>
</bean>
<!-- 将SqlSessionFactory配置进spring中 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 设置MyBatis核心配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
<!-- 设置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 别名包扫描 -->
<property name="typeAliasesPackage" value="com.project.mybatis.pojo" />
</bean>
<!-- 配置mapper扫描包 -->
<!-- <bean class="">
</bean> -->
<bean class="com.project.mybatis.dao.Impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
5、Dao的开发
(1)创建javabean
package com.project.mybatis.pojo;
public class User {
private String id;
private String username;
private String birthday;
private String sex;
private String address;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
+ address + "]";
}
}
(2)创建UserDao接口(传统方式,也可以用官方推荐方式,接口不用自己写实现类)
package com.project.mybatis.dao;
import java.util.List;
import com.project.mybatis.pojo.User;
public interface UserDao {
User getUserById(Integer id);
List<User> getUserByUserName(String username);
void insertUser(User user);
}
(3)接口实现类UserDaoImpl
package com.project.mybatis.dao.Impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.project.mybatis.dao.UserDao;
import com.project.mybatis.pojo.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
@Override
public User getUserById(Integer id) {
SqlSession sqlSession = super.getSqlSession();
User user = sqlSession.selectOne("user.getUserById",id);
return user;
}
@Override
public List<User> getUserByUserName(String username) {
SqlSession sqlSession = super.getSqlSession();
List<User> users = sqlSession.selectList("user.getUserByUserName",username);
return users;
}
@Override
public void insertUser(User user) {
SqlSession sqlSession = super.getSqlSession();
sqlSession.insert("user.insertUser", user);
}
}
(4)根据接口创建测试类,用单元测试
package com.project.mybatis.test;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.project.mybatis.dao.UserDao;
import com.project.mybatis.pojo.User;
public class UserDaoTest {
private ApplicationContext applicationContext;
@Before
public void init() {
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");//要不要写classpath?
}
@Test
public void testGetUserById() {
UserDao userDao = applicationContext.getBean(UserDao.class);
User user = userDao.getUserById(1);
System.out.println(user);
}
@Test
public void testGetUserByUserName() {
UserDao userDao = applicationContext.getBean(UserDao.class);
List<User> users = userDao.getUserByUserName("张");
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testInsertUser() {
fail("Not yet implemented");
}
}
(5)user.xml文件,这个应该在Dao之前创建
<?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.project.mybatis.pojo.User">
<select id="getUserById" returnType="com.project.mybatis.pojo.User" parameterType="int">
select * from user where id = #{id}
</select>
<select id="getUserByUserName" parameterType="String" returnType="usecom.project.mybatis.pojo.Userr">
select * from user where id = %${value}%
</select>
<insert id="insertUser" parameterType="com.project.mybatis.pojo.User">
insert into user (username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address});
</insert>
</mapper>
(6)运行测试类。
以上是我的基本思路,有了思路才能好好的干活。当然上面的mysql数据库环境要弄好,还有就是数据库的字段和javabean的一一对应,当然还有数据库的密码和账号要修改成自己的。mybatis是一个非常优秀的持久层框架,在国内现在主流的主要是Hibernate和mybatis,但是Hibernate入门比较难,而且精通更难,所以hibernate的精通人才比mybatis的少,特别是表之间的映射关系设计。再者就是mybatis的SQL比较灵活,易维护。有什么不对的地方请多指教~
推荐阅读
-
Spring-Data-JPA整合MySQL和配置的方法
-
使用maven整合Spring+SpringMVC+Mybatis框架详细步骤(图文)
-
SpringMVC+Spring+Mybatis实现支付宝支付功能的示例代码
-
Spring MVC+FastJson+hibernate-validator整合的完整实例教程
-
Spring Boot 与 Kotlin 使用Redis数据库的配置方法
-
spring boot与spring mvc的区别及功能介绍
-
详解spring cloud整合Swagger2构建RESTful服务的APIs
-
Spring Boot整合mybatis(一)实例代码
-
spring Boot与Mybatis整合优化详解
-
详解Spring Boot中MyBatis的使用方法