Mybatis使用
使用IDEA,创建maven项目,新建后如下
在src下新建java,resources以及测试用的Java和resources包,新建时IDEA会有提示直接选择。
一、引入依赖
在pom.xml中引入依赖
junit依赖、mybatis 依赖、mysql 依赖 、 log4j 日志依赖
<dependencies>
<!--junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- mybatis 依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
<scope>runtime</scope>
</dependency>
<!-- log4j 日志依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
二、xml配置文件(Configuration)
通常是classpath下的SqlMapConfig.xml文件。
在resources下创建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>
<!-- 配置 mybatis 的环境 -->
<environments default="mysql">
<!-- 配置 mysql 的环境 -->
<environment id="mysql">
<!-- 配置事务的类型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置连接数据库的信息:⽤的是数据源(连接池) -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="961856379"/>
</dataSource>
</environment>
</environments>
<!-- 告知 mybatis 映射配置的位置 -->
<mappers>
<mapper resource="com/zzxx/dao/IUserDao.xml"/>
</mappers>
</configuration>
mybatis的核心配置文件中里面的配置是有顺序的如下:
1.properties,2.settings,3.typeAliases,4.typeHandlers,5.objectFactory,5.objectWrapperFactory,6.reflectorFactory,7.plugins,8.environments,9.databaseIdProvider,10.mappers
配置文件中的实际内容要按实际情况更改,如数据库的配置信息、mappers里的映射配置文件等
log4j日志配置文件
log4j.properties创建在resources文件夹下
# 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
三、数据库准备
创建所需数据库数据
DROP TABLE IF EXISTS role
;
CREATE TABLE role
(
ID
int NOT NULL COMMENT ‘编号’,
ROLE_NAME
varchar(30) DEFAULT NULL COMMENT ‘角色名称’,
ROLE_DESC
varchar(60) DEFAULT NULL COMMENT ‘角色描述’,
PRIMARY KEY (ID
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
BEGIN;
INSERT INTO role
VALUES (1, ‘院长’, ‘管理整个学院’);
INSERT INTO role
VALUES (2, ‘总裁’, ‘管理整个公司’);
INSERT INTO role
VALUES (3, ‘校长’, ‘管理整个学校’);
COMMIT;
DROP TABLE IF EXISTS user
;
CREATE TABLE user
(
id
int NOT NULL AUTO_INCREMENT,
username
varchar(32) NOT NULL COMMENT ‘用户名称’,
birthday
datetime DEFAULT NULL COMMENT ‘生日’,
sex
char(1) DEFAULT NULL COMMENT ‘性别’,
address
varchar(256) DEFAULT NULL COMMENT ‘地址’,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8;
BEGIN;
INSERT INTO user
VALUES (41, ‘老王’, ‘1991-02-27 17:47:08’, ‘男’, ‘杭州’);
INSERT INTO user
VALUES (42, ‘小二王’, ‘1989-03-02 15:09:37’, ‘女’, ‘杭州下沙’);
INSERT INTO user
VALUES (43, ‘小二王’, ‘1987-03-04 11:34:34’, ‘女’, ‘杭州高沙’);
INSERT INTO user
VALUES (45, ‘指针信息’, ‘1992-03-04 12:04:06’, ‘男’, ‘杭州东沙’);
INSERT INTO user
VALUES (46, ‘老王’, ‘1989-03-07 17:37:26’, ‘男’, ‘杭州金沙’);
INSERT INTO user
VALUES (48, ‘小马宝莉’, ‘1990-03-08 11:44:00’, ‘女’, ‘杭州东’);
COMMIT;
DROP TABLE IF EXISTS user_role
;
CREATE TABLE user_role
(
UID
int NOT NULL COMMENT ‘用户编号’,
RID
int NOT NULL COMMENT ‘角色编号’,
PRIMARY KEY (UID
,RID
),
KEY FK_Reference_10
(RID
),
CONSTRAINT FK_Reference_10
FOREIGN KEY (RID
) REFERENCES role
(ID
),
CONSTRAINT FK_Reference_9
FOREIGN KEY (UID
) REFERENCES user
(id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
BEGIN;
INSERT INTO user_role
VALUES (41, 1);
INSERT INTO user_role
VALUES (45, 1);
INSERT INTO user_role
VALUES (41, 2);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
DROP TABLE IF EXISTS account
;
CREATE TABLE account
(
ID
int NOT NULL COMMENT ‘编号’,
UID
int DEFAULT NULL COMMENT ‘用户编号’,
MONEY
double DEFAULT NULL COMMENT ‘金额’,
PRIMARY KEY (ID
),
KEY FK_Reference_8
(UID
),
CONSTRAINT FK_Reference_8
FOREIGN KEY (UID
) REFERENCES user
(id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
BEGIN;
INSERT INTO account
VALUES (1, 41, 1000);
INSERT INTO account
VALUES (2, 45, 1000);
INSERT INTO account
VALUES (3, 41, 2000);
COMMIT;
四、实体类准备
这里创建例子User实体类,其中创建的实体类属性名要与User表中的字段名一致(如果不一致。。。,后面也有resultMap来解决,不过这里可能来不及写)
五、准备接口
提供查询的方法
六、创建映射文件
位置名称要与相应的接口名称相一致,配置按实际情况写(mapper namespace=""),在标签下标签中写数据操作语句,标签中的id和接口中相应的方法名称一致,resultType为结果类型
<?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.zzxx.dao.UserDao">
<!-- 配置查询所有操作 -->
<select id="findAll" resultType="com.zzxx.domain.User">
select * from user
</select>
</mapper>
创建完以后的目录结构如下
七、在配置文件(SqlMapConfig.xml)中注册mapper
在mapper标签内告知映射配置文件的位置
八、测试
import com.zzxx.dao.UserDao;
import com.zzxx.domain.User;
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 org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserTest {
InputStream in;
SqlSession session;
UserDao userDao;
@Before
public void before() throws IOException {
// 1.读取配置⽂件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2.创建 SqlSessionFactory 的构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 3.使⽤构建者创建⼯⼚对象 SqlSessionFactory
SqlSessionFactory factory = builder.build(in);
// 4.使⽤ SqlSessionFactory ⽣产 SqlSession 对象
session = factory.openSession();
// 5.使⽤ SqlSession 创建 dao 接⼝的代理对象
userDao = session.getMapper(UserDao.class);
}
@Test
public void findAllTest() throws IOException {
// 6.使⽤代理对象执⾏查询所有⽅法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
}
}
测试结果: