层
- Service是业务层,Dao层是数据访问层,这样的分层是基于MVC架构来说的,分层的主要作用是解耦。
- 对于Spring这样的框架,(View/Web)表示层调用控制层(Controller),控制层调用业务层(Service),业务层调用数据访问层(Dao)
- 具体起来,Dao的作用是封装对数据库的访问:增删查改,不涉及业务逻辑,只是达到按某个条件获得指定数据的要求;而Service,则是专注业务逻辑,对于其中需要的数据库操作,都通过Dao去实现;
看官方文档
- MyBatis是一款优秀的持久层 框架,本是apache的一个开源项目iBatis,后迁移到google code ,后迁移到GitHub
- 定制化sql
- 几乎避免了所有的jdbc代码
如何获得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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&character=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/yst/dao/UserMapper.xml"/>
</mappers>
</configuration>
-
UserMapper.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.yst.dao.UserMapper">
<select id="getUserList" resultType="com.yst.pojo.User">
select * from mybatis.user
</select>
<select id="getUserByID" parameterType="int" resultType="com.yst.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<insert id="insertUser" parameterType="com.yst.pojo.User">
insert into mybatis.user(id, name, password) values(#{id},#{name},#{password})
</insert>
<update id="updateUser" parameterType="com.yst.pojo.User">
update mybatis.user set name = #{name},password = #{password} where id =#{id}
</update>
<delete id="deleteUser" parameterType="com.yst.pojo.User">
delete from mybatis.user where id = #{id}
</delete>
</mapper>
-
MyBatisUtils package com.yst.utils;
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 MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
-
test package com.yst.dao;
import com.yst.pojo.User;
import com.yst.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userByID = mapper.getUserByID(1);
System.out.println(userByID);
sqlSession.close();
}
@Test
public void insertUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.insertUser(new User(6,"yst","123345"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(1,"yst","123456"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(2);
sqssion.commit();
sqlSession.close();
}
}
配置优化
- 导入外部properties
- typeAliase 别名
- settings设置
总结
-
创建一个干净的maven项目 -
配置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>org.example</groupId>
<artifactId>MyBatis-Study</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>MyBatis-01</module>
<module>MyBatis-02</module>
<module>MyBatis-03</module>
<module>Mybatis-04</module>
<module>Mybatis-05</module>
<module>Mybatis-06</module>
<module>MyBatis-07</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
-
在src/java目录下创建package (dao、pojo、utils) -
dao下写接口和映射mapper(名字最好一样)
-
UserMapper.java package com.yst.dao;
import com.yst.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
public User getLoginUser(@Param("userCode") String userCode);
public int add(User user);
public List<User> getUserList(@Param("userPassword") String userPassword,@Param("userRole") Integer userRole,
@Param("from") Integer currentPageNo,@Param("pageSize") Integer PageSize);
}
-
UseMapper.xml <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yst.dao.UserMapper">
<select id="getLoginUser" parameterType="String" resultType="user">
select * from smbms.smbms_user
where userCode=#{userCode}
</select>
<insert id="add" parameterType="user">
insert into smbms.smbms_user(id, userCode, userName, userPassword,
gender, birthday, phone, address, userRole, createdBy, creationDate, modifyBy, modifyDate)
VALUES
(#{id},#{userCode},#{userName},#{userPassword},
#{gender},#{birthday},#{phone},#{address},#{userRole},#{createdBy},
#{creationDate},#{modifyBy},#{modifyDate})
</insert>
<select id="getUserList" resultType="user">
select * from smbms.smbms_user
where userPassword=#{userPassword}
and userRole=#{userRole}
limit #{from},#{pageSize}
</select>
</mapper>
-
utils工具类 package com.yst.utils;
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 MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
-
resources目录下放最主要的配置文件
-
db.properties driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=123456
-
log4j.properties #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
-
mybatis-config.xml MyBatis核心配置文件 <?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="log4j"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.yst.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/yst/dao/UserMapper.xml"/>
</mappers>
</configuration>
-
test/java 测试 import com.yst.dao.UserMapper;
import com.yst.pojo.User;
import com.yst.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class MyTest {
@Test
public void getLoginUserByUserCode(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User admin = mapper.getLoginUser("admin");
System.out.println(admin);
sqlSession.close();
}
@Test
public void insertUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.add(new User(18,"zhangqiang","张强","000000",1,new Date(),"13230992245","Beijing,China",1,1,new Date(),1,new Date()));
sqlSession.commit();
sqlSession.close();
}
@Test
public void getUserList() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList("0000000", 3, 1, 99);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
- 导入junit的jar包,使用注解方便测试
- 调用MybatisUtils工具类建立sqlSession,使用sqlSession调用接口方法,完成对数据的操作。
-
学习过程
- 阅读官方文档
- 配置环境
- 创建数据库,实体类,测试类
- 测试
- 解决报错问题
- 练习
|