Top

MyBatis 的基础使用(增删查改) 以及配置 Log4j 日志模块



1、配置 Mavan 依赖

pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
</dependencies>

在 IntelliJ IDEA 中,还需要配置如下代码,否则不会编译 xml ,导致找不到配置文件 (这里踩坑了)

pom.xml
1
2
3
4
5
6
7
8
9
10
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>

2、MyBatis 配置文件

mybatis_config.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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="mysql">
<environment id="mysql">
<!-- 配置事务处理,一般用JDBC -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源 -->
<dataSource type="POOLED">
<!-- mysql数据库的配置信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/store"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 单文件形式注册 Mapper -->
<mapper resource="net/crazykid/mapper/categoryMapper.xml"/>
<mapper resource="net/crazykid/mapper/productMapper.xml"/>

<!--package方式注册,该包下所有mapper自动注册-->
<package name="net.crazykid.mapper"/>
</mappers>
</configuration>

3、pojo类

Category.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package net.crazykid.bean;

import java.util.List;

public class Category {
private String cid;
private String cname;
private List<Product> products;


public Category(){}

public Category(String cid, String cname, List<Product> products) {
this.cid = cid;
this.cname = cname;
this.products = products;
}

public String getCid() {
return cid;
}

public void setCid(String cid) {
this.cid = cid;
}

public String getCname() {
return cname;
}

public void setCname(String cname) {
this.cname = cname;
}

public List<Product> getProducts() {
return products;
}

public void setProducts(List<Product> products) {
this.products = products;
}

@Override
public String toString() {
return "Category{" +
"cid='" + cid + '\'' +
", cname='" + cname + '\'' +
", products=" + products +
'}';
}
}

4、Mapper 的编写

1
2
3
4
5
6
7
8
<?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="net.crazykid.mapper.categoryMapper">
<!-- 这里写内容... -->
</mapper>

4.1 插入语句

  • parameterType: 传入参数的类型
1
2
3
<insert id="Insert" parameterType="net.crazykid.bean.Category">
INSERT INTO category (cid, cname) VALUES (#{cid}, #{cname});
</insert>

4.2 删除语句

注: parameterTypeString 时,用 #{_parameter}

1
2
3
<delete id="deleteCategoryById" parameterType="String">
DELETE FROM category WHERE cid = #{_parameter};
</delete>

4.3 查询语句

  • resultType: 返回结果的类型
查询全部内容
1
2
3
<select id="selectAllCategory" resultType="net.crazykid.bean.Category">
SELECT * from category;
</select>
根据 ID 查询
1
2
3
<select id="selectCategoryById" parameterType="Int" resultType="net.crazykid.bean.Category">
SELECT * FROM category WHERE cid = #{cid}
</select>
多条件查询
1
2
3
4
5
6
7
<select id="selectMultiCategoryById" resultType="net.crazykid.bean.Category">
SELECT * FROM category WHERE cid IN
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
动态查询语句
categoryMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- 定义一个结果集合 -->
<resultMap id="categoryMap" type="net.crazykid.bean.Category">
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>

<!-- 一对多关联查询 -->
<collection column="cid" property="products" ofType="net.crazykid.bean.Product" select="net.crazykid.mapper.productMapper.selectProductByCId">
</collection>
</resultMap>

<!--动态查询语句-->
<!-- resultMap 指定自定义的结果集合名称 -->
<select id="selectCategory" parameterType="java.util.Properties" resultType="net.crazykid.bean.Category" resultMap="categoryMap" >
SELECT * FROM category
<where>
<if test="cid != null">
AND cid = #{cid}
</if>
<if test="cname != null">
AND cname = #{cname}
</if>
</where>
</select>

多对一关联查询….(这是另一个类另一个mapper)

1
2
3
4
<resultMap id="productMap" type="net.crazykid.bean.Product" extends="baseMap">
<association column="cid" property="category" javaType="net.crazykid.bean.Category" select="net.crazykid.mapper.categoryMapper.selectCategoryById">
</association>
</resultMap>

5、Mapper 的实现类

categoryMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface categoryMapper {
//这是上面写好的 Mapper 的实现方法
void Insert(Category category);
List<Category> selectAllCategory();
List<Category> selectCategory(Properties properties);
void deleteCategoryById(String id);
List<Category> selectMultiCategoryById(List list);

//这是基于注解的方法,不用写 Mapper ...
@Select("SELECT * FROM category where cid=#{cid}")
List<Category> selectAllCategory2(String cid);

//类似的注解还有 @Insert @Delete @Update....
}

6、测试类

categoryTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class categoryTest {
SqlSessionFactory sessionFactory = null;
InputStream inputStream = null;

@Before
public void init(){
try {
inputStream = Resources.getResourceAsStream("mybatis_config.xml");
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void testInsert() {
SqlSession session = sessionFactory.openSession();
categoryMapper CategoryMapper=session.getMapper(categoryMapper.class);

Category category = new Category();
category.setCid("123");
category.setCname("阔落");

CategoryMapper.Insert(category);
session.commit();
session.close();
}

@Test
public void testSelectAllCategory() {
SqlSession session = sessionFactory.openSession();
categoryMapper CategoryMapper=session.getMapper(categoryMapper.class);

List<Category> list = CategoryMapper.selectAllCategory();
System.out.println(list);
}

@Test
public void testSelectCategory() {
SqlSession session = sessionFactory.openSession();
categoryMapper CategoryMapper=session.getMapper(categoryMapper.class);

Properties properties = new Properties();
properties.setProperty("cid", "1");
//properties.setProperty("cname", "aaaa");

List<Category> list = CategoryMapper.selectCategory(properties);
System.out.println(list);
}

@Test
public void testDeleteCategoryById() {
SqlSession session = sessionFactory.openSession();
categoryMapper CategoryMapper=session.getMapper(categoryMapper.class);

CategoryMapper.deleteCategoryById("aaa2");
}

@Test
public void testSelectMultiCategoryById() {
SqlSession session = sessionFactory.openSession();
categoryMapper CategoryMapper=session.getMapper(categoryMapper.class);


List li = new ArrayList();
li.add(1);
li.add(2);

List<Category> list = CategoryMapper.selectMultiCategoryById(li);
System.out.println(list);
}

@Test
public void testSelectAllCategory2() {
SqlSession session = sessionFactory.openSession();
categoryMapper CategoryMapper=session.getMapper(categoryMapper.class);

List<Category> list = CategoryMapper.selectAllCategory2("6");
System.out.println(list);
}
}

7、整合 Log4j

7.1 导入 Log4j 包

pom.xml
1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

7.2 引入 Log4j

踩坑记录: 必须按照指定的顺序放置标签,如 <setting> 不能放在 <environments> 或者 <mappers> 的后面,否则会报错!!

mybatis_config.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<configuration>
<!--集成Log4j-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>

<environments default="mysql">
...
</environments>

<mappers>
...
</mappers>
</configuration>

7.3 Log4j 的配置文件

log4j.properties
1
2
3
4
5
6
7
8
9
10
11
# 全局日志配置
log4j.rootLogger=ERROR, stdout
# 指定Mapper的日志配置
log4j.logger.net.crazykid.mapper.categoryMapper=TRACE
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

# 对于命名空间为 net.crazykid.mapper.categoryMapper 的 Mapper,日子级别为 Trace
# 其余的则为全局配置级别 Error, stdout

 发表评论

文明评论,请勿灌水。为防止恶意评论,请登录账号后发表评论