1、什么MyBatis
注:《3、CURD 增删改查》中有完成配置代码和文件夹命名截图
前身:MyBatis 本是apache的一个开源项目iBatis 未来我们编写代码的时候,导入包的时候,ibatis;
MyBatis:需要在 Github 上下载!
GitHub地址:https://github.com/mybatis/mybatis-3
当前,最新版本是MyBatis 3.5.4 ,其发布时间是2020年2月4日。
官网地址:https://mybatis.org/mybatis-3/
MyBatis特性:
- MyBatis 是一款优秀的持久层框架
- 它支持定制化 SQL、存储过程以及高级映射。
- MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
- MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
2、第一个程序
1、准备一个数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`)
VALUES (1,'周丹','123456'),(2,'周颖','zxcvbn'),(3,'姜嘉航','123456');
2、准备jar包,Maven 加上连接数据库的jar包
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
3、第一步配置文件编写 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/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
4、 编写一个工具类操作数据库
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();
}
}
// 获取sqlSession的连接
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
5、 配置了一个实体类,引入了Lombok
首先需要加载Lombok的jar包
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
6、 持久层的操作接口
// 操作用户的接口类
public interface UserMapper {
List<User> getUserList();
}
7、 原来我们需要编写接口实现类,使用了Mybatis之后,我们可以专注编写SQL,使用配置文件
- 好处,程序运行起来之后,我依旧可以动态修改代码,解耦、
注意点:1、namespace 绑定对应的接口,2、具体操作(CRUD)表情对应的id,为接口中的方法,
<?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">
<!-- 原来我们都是编写具体的执行sql -->
<mapper namespace="com.g'ggg.mapper.UserMapper">
gg
<select id="getUserList" resultType="com.g'g.pojo.User">
select * from user;
</select>
</mapper>
8、这个配置文件一定要注册到Mybatis的配置文件中
<mappers>
<mapper resource="com/kuang/mapper/UserMapper.xml"/>
</mappers>
9、测试运行
public class Test {
public static void main(String[] args) {
// 如何获取接口
// 1、 获取SqlSession, 执行sql使用的
SqlSession session = MyBatisUtils.getSession();
// 2、通过 session.getMapper(Class ) 获得接口
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
}
3、CURD 增删改查
固定操作
1、编写接口
2、编写接口对应的SQL配置文件,一定要确保配置文件和SQL的正确性
3、测试
1、通过id 查询用户 User selectById(int id);
2、通过用户名和密码查询用户 User selectByUsernamePwd(String username, String pwd);
3、新增一个用户 int addUser(User user);
4、修改用户信息 int updateUser(User user);
5、删除一个用户 int deleteUserByID(int id);
注意点
1、多个参数一定要增加 @Param 注解
2、增删改一定要增加事务提交
3、增删改,标签一定要对应,参数类型必须要写
4、增删改不用写返回值,查询,必须写返回值,集合、泛型中的内容(具体的对象)
下面是完整的增删改查代码
Test
import com.gg.mapper.Users;
import com.gg.pojo.User;
import com.gg.utils.Util;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Test {
public static void main(String[] args) {
SqlSession session = Util.getSession();
Users users = session.getMapper(Users .class);
List<User> list = users.getUsers();
for (User user : list) {
System.out.println(user);
}
User userById = users.getUserById(1);
System.out.println(userById);
User zd = users.selectByUsernamePwd("周丹", "123456");
System.out.println(zd);
int add = users.addUser(new User(5, "郭建", "123456"));
session.commit();
if (add>0){
System.out.println("增加成功");
}
int up = users.updateUser(new User(1, "郭建", "123456"));
session.commit();
if (up>0){
System.out.println("修改成功");
}
}
}
Users
package com.gg.mapper;
import com.gg.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface Users {
List<User> getUsers();
User getUserById(int id);
User selectByUsernamePwd(@Param("username") String username, @Param("pwd")String pwd);
int addUser(User user);
int updateUser(User user);
}
User
public class User {
private int id;
private String name;
private String pwd;
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getPwd() {
return pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
Util
package com.gg.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 Util {
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();
}
}
// 获取sqlSession的连接
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
Users.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.gg.mapper.Users">
<select id="getUsers" resultType="com.gg.pojo.User">
select * from user;
</select>
<select id="getUserById" resultType="com.gg.pojo.User">
select * from user where id=#{id};
</select>
<select id="selectByUsernamePwd" resultType="com.gg.pojo.User">
select * from user where name =#{username} and pwd = #{pwd};
</select>
<insert id="addUser" parameterType="com.gg.pojo.User">
INSERT INTO `user` (`id`, `name`, `pwd`) VALUES (#{id}, #{name}, #{pwd});
</insert>
<update id="updateUser" parameterType="com.gg.pojo.User">
update `user` set `name` = #{name} where id=#{id};
</update>
</mapper>
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/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.gg.mapper"/>
</mappers>
</configuration>
4、配置文件
1、配置mappper映射器 为扫描包的
这样
<typeAliases>
<package name="com.gg.pojo"/>
</typeAliases>
<mapper namespace="com.gg.mapper.UserMapper">
<select id="getUserList" resultType="User">
select * from user;
</select>
2、配置db.properties 让配置文件读取
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis? useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=123456
<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>
3、配置类型的别名,简化开发
4、通过settings 配置日志
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
5、ResultMap
问题:假如属性名和字段名不一致!
实体类的属性为password而数据库中的为pwd
private int id;
private String name;
private String password;
将pwd映射到password上即可
<mapper namespace="com.gg.mapper.UserMapper">
<resultMap id="a" type="User">
<result column="pwd" property="password"/>
</resultMap>
<select id="getUser" resultMap="a">
select * from user where id=#{id};
</select>
</mapper>
如果属性名和数据库的列名,一致 ,这个时候mybatis 会帮我们自动推断!=>自动映射
如果属性名和数据库的列名,不一致 ,手动实现映射
示例:首先创建数据库文件
工具类和相关配置
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 getSession(){
return sqlSessionFactory.openSession();
}
}
<?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>
<setting name="cacheEnabled" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.gg.pojo"/>
</typeAliases>
<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/mybatis? useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.gg.mapper"/>
</mappers>
</configuration>
一对多:一个老师查询该老师下面的所有学生
@org.junit.Test
public void getTeacher(){
SqlSession session = MyBatisUtils.getSession();
TeacherMapper mapper = session.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
}
@Data
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
@Data
public class Student {
private int id;
private String name;
private int tid;
}
public interface TeacherMapper {
Teacher getTeacher(int id);
}
<?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.gg.mapper.TeacherMapper">
<resultMap id="TeacherStudent" type="Teacher">
<id column="tid" property="id"/>
<result column="tname" property="name"/>
<collection property = "students" ofType="Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="tid" property="tid"/>
</collection>
</resultMap>
<select id="getTeacher" resultMap="TeacherStudent">
SELECT s.id sid,s.name sname,t.name tname,t.id tid
FROM student s,teacher t
WHERE s.tid=t.id AND t.id=#{id}
</select>
</mapper>
多对一:多个学生查询学生和其同一个老师
@org.junit.Test
public void getStudents(){
SqlSession session = MyBatisUtils.getSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
List<Student> students = mapper.getStudents();
for (Student student : students) {
System.out.println(student);
}
}
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
@Data
public class Teacher {
private int id;
private String name;
}
public interface StudentMapper {
List<Student> getStudents();
}
<?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.gg.mapper.StudentMapper">
<resultMap id="StudentTeacher" type="com.gg.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.gg.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
<select id="getStudents" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.id tid,t.name tname
from Student s,Teacher t
where t.id=s.tid
</select>
</mapper>
6、分页(一定要会的)
日志:Log4j
为什么要使用日志;
跑了一个代码,只能看到 结果!结果有错误了。排除错误!
MyBatis日志:
<settings>
<!--配置日志,就可以看到具体的SQL信息,从而找到出错的原因!-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
工作中我们用的更多的 log4j;Apache
如何使用Log4j
1、导入包依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、编写log4j的配置文件
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ./log/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =./log/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
3、修改日志实现为 Log4j,注意大小写问题即可
<settings>
<!--配置日志,就可以看到具体的SQL信息,从而找到出错的原因!
切换为Log4j 的之后,大小写问题
-->
<setting name="logImpl" value="LOG4J"/>
</settings>
4、假设我们要使用Log4j 的类去打印日志
import com.kuang.mapper.RMapper;
import com.kuang.pojo.User;
import com.kuang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
public class Test1 {
// 注意导入包的问题 org.apache.log4j.Logger
static Logger logger = Logger.getLogger(Test1.class);
public static void main(String[] args) {
SqlSession session = MyBatisUtils.getSession();
RMapper mapper = session.getMapper(RMapper.class);
System.out.println("1231321222222");// 普通的输出
// 通过log4j 可以将日志实现细粒度的控制;
logger.error("1231321222222"); // 错误信息
logger.info("1231321222222"); // 提示信息
logger.debug("1231321222222");
// 属性名和字段不一致!
User user = mapper.selectUserById(1);
System.out.println(user);
}
}
为什么要分页:提高服务器性能!按照一小部分一小部分的来处理我们的数据!
Limit
Select * from user limit startIndex,Pagesize
代码:
Test
public class Test {
public static void main(String[] args) {
SqlSession session = MyBatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<String, Integer>();
int startIndex = 1;
int size = 3;
map.put("startIndex",(startIndex-1)*size);
map.put("size",size);
List<User> users = mapper.selectUsersByLinmit(map);
for (User user : users) {
System.out.println(user);
}
}
}
UserMapper
public interface UserMapper {
List<User> getUserList();
User getUser(int id);
List<User> selectUsersByLinmit(Map<String,Integer> map);
}
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.gg.mapper.UserMapper">
<resultMap id="a" type="User">
<result column="pwd" property="password"/>
</resultMap>
<select id="selectUsersByLinmit" parameterType="map" resultMap="a">
select * from user limit #{startIndex},#{size}
</select>
</mapper>
注:其他未写代码与之前的一样就行,上述只是改写的代码