使用mybatis当然是取代JDBC来操作数据库啦。
因为mybatis是基于JDBC实现的,所以mybatis的销量是低于JDBC的。
环境搭建 数据库建表
创建数据库:
CREATE DATABASE echotest;
创建表:
DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user (
id char(32) NOT NULL,
user_name varchar(32) DEFAULT NULL,
password varchar(32) DEFAULT NULL,
name varchar(32) DEFAULT NULL,
age int(10) DEFAULT NULL,
sex int(2) DEFAULT NULL,
birthday date DEFAULT NULL,
created datetime DEFAULT NULL,
updated datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入数据:
INSERT INTO echotest.tb_user (id, user_name, password, name, age, sex, birthday, created, updated) VALUES ( 1,"钱", "123456", "佩雨", 22, 1, "2000-09-02", sysdate(), sysdate());
INSERT INTO echotest.tb_user ( id,user_name, password, name, age, sex, birthday, created, updated) VALUES ( 2,"秦", "123456", "狂神", 22, ‘1’, "1990-09-05", sysdate(), sysdate());
INSERT INTO echotest.tb_user ( id,user_name, password, name, age, sex, birthday, created, updated) VALUES ( 3,"小", "666666", "可爱", 5, 2, "2019-02-05", sysdate(), sysdate());
使用mybatis来操作数据库
step1
导入mybatis的包 和导入jdbc的包 在pom.xml中导入
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
step2
配置mybatis-config.xml
<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/echotest?useUnicode=true&characterEncoding=utf-8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="*******"/>
dataSource>
environment>
environments>
configuration>
Step3 编写各模块代码
整体工程如下
编写UserMapper.xml
<mapper namespace="dao.UserMapper">
<select id="getUserList" resultType="User">
select * from tb_user
select>
mapper>
在全局的mybatis-config.xml中增加我们写的UserMapper
<mappers>
<mapper resource="dao/UserMapper.xml">mapper>
mappers>
编写其他代码 余下:
User.java
package pojo;
import java.util.Date;
public class User {
private int id;
private String userName;
private String password;
private String name;
private int age;
private int sex;
private String birthday;
private Date created;
private Date updated;
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", birthday='" + birthday + '\'' +
", created=" + created +
", updated=" + updated +
'}';
}
public User(int id, String userName, String password, String name, int age, int sex, String birthday, Date created, Date updated) {
this.id = id;
this.userName = userName;
this.password = password;
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.created = created;
this.updated = updated;
}
public int getId() {
return id;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getSex() {
return sex;
}
public String getBirthday() {
return birthday;
}
public Date getCreated() {
return created;
}
public Date getUpdated() {
return updated;
}
public void setId(int id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(int sex) {
this.sex = sex;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setCreated(Date created) {
this.created = created;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
UserMapper.java
package dao;
import pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
}
mybatis-config.xml
<configuration>
<typeAliases><typeAlias type="pojo.User" alias="User"/> 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/echotest?useUnicode=true&characterEncoding=utf-8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="qpy939773"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="dao/UserMapper.xml">mapper>
mappers>
configuration>
Test.java
import dao.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 pojo.User;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test {
public static void main(String[] args) {
// 读取mybatis的全局配置
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
// 根据配置建立出sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// sqlSession是我们操作的对象
// 使用正确描述每个语句的参数和返回值的接口
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 查询数据库所有User打印
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
操作成功可以读取出数据:
Mapper里面是支持动态配置sql的,这里面有很多标签如下,支持数据库的增删改查。
下面展示了一些增删改查的基本语句。
Mapper中支持数据库到实体类的映射,当pojo中的属性名和数据库中的列名不一致的时候,我们可以通过
自定义resultMap
来进行映射。
properties配置的属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。例如:
我们只需要在db.properties里面配置数据源即可。
如果属性在不只一个地方进行了配置,那么 MyBatis 将按照下面的顺序来加载:
我们需要告诉 MyBatis 到哪里去找到这些语句。 Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:///
的 URL),或类名和包名等。例如: