使用 Maven 完成 dao 层
# 100.使用 Maven 完成 dao 层
我们先使用 Maven 做一些实际的事情,方便后续的知识点的引入。
# 创建数据库
我们创建一个数据库、用户和一张表:
create database learnmaven;
use learnmaven;
CREATE USER IF NOT EXISTS LearnMavenUser@'%' IDENTIFIED BY 'LearnMavenUser@Password';
GRANT ALL PRIVILEGES ON learnmaven.* TO LearnMavenUser@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`id` int(10) NOT NULL auto_increment,
`name` varchar(20) default NULL,
`price` float(10,0) default NULL,
`pic` varchar(40) default NULL,
`createtime` datetime default NULL,
`detail` varchar(200) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '王小美', '1000', null, '2023-05-13 09:29:30', '带我走上人生巅峰');
INSERT INTO `items` VALUES ('2', '刻晴猫', null, null, '2023-05-28 10:05:52', '插入测试');
INSERT INTO `items` VALUES ('3', '胡桃', '199', null, '2023-05-07 10:08:04', '插入测试');
INSERT INTO `items` VALUES ('7', '影', null, null, null, null);
INSERT INTO `items` VALUES ('8', '狐狸', null, null, null, null);
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
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
# 创建一个新的 Maven 项目
我们使用 IDEA 创建一个新的 Maven 工程,骨架选择 webapp 的,并且新建 src/main/java 目录,此时目录结构如下:
修改 web.xml 文件:原先的 web-app
标签里没有配置 xmlns 等名称空间,我们补上:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
修改 pom.xml:我们只保留一些必备的属性,其他的我们先删掉
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.peterjxl</groupId>
<artifactId>LearnJavaMaven</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>LearnJavaMaven Maven Webapp</name>
</project>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 添加依赖
这里我们引用 SSM 的依赖,由于依赖很多,这里我们就不贴出代码了,读者可以去 GitHub (opens new window) 和 Gitee (opens new window) 里拷贝。
# 添加 Log4j 配置
为了方便输出日志,我们添加 resources/log4j.properties 配置文件:
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 新建 dao 实体类
package com.peterjxl.domain;
import java.util.Date;
public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
注:自行生成 getter 和 setter 方法
# 新增 dao 接口
package com.peterjxl.dao;
import com.peterjxl.domain.Items;
public interface ItemsDao {
Items findById(Integer id);
}
1
2
3
4
5
2
3
4
5
# 新建 Mybatis 映射文件
新建 resources\com\peterjxl\dao\ItemsDao.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.peterjxl.dao.ItemDao">
<select id="findById" parameterType="int" resultType="items">
select * from items where id = #{id}
</select>
</mapper>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
下一步应该就是创建 Mybatis 的主配置文件,但由于我们用到了 SSM,我们的配置文件信息交给 Spring 来管理即可
# 创建 Spring 配置文件
创建 resources/applicationContext.xml,并引入约束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
然后我们配置 dao 层:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///learnmaven"/>
<property name="username" value="LearnMavenUser"/>
<property name="password" value="LearnMavenUser@Password"/>
</bean>
<!-- 配置生成 SqlSession 对象的工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.peterjxl.learn.*.model"/>
<!--扫描pojo包,给包下所有pojo对象起别名-->
<property name="typeAliases" value="com.peterjxl.domain"/>
</bean>
<!-- 扫描接口包路径,并生成所有接口的代理对象,放到 Spring 容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.peterjxl.dao"/>
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 新建测试类
package com.peterjxl.test;
import com.peterjxl.dao.ItemsDao;
import com.peterjxl.domain.Items;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ItemsTest {
@Test
public void findById() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从容器中拿到所需的dao的代理对象
ItemsDao itemDao = ac.getBean("itemsDao", ItemsDao.class);
Items items = itemDao.findById(1);
System.out.println(items);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
运行结果:
Items{id=1, name='王小美', price=1000.0, pic='null', createtime=Sat May 13 09:29:30 CST 2023, detail='带我走上人生巅峰'}
1
# 源码
已将所有代码上传到 Gitee (opens new window) 和 GitHub (opens new window) 上,本文中涉及到的代码在分支 demo4Dao。
上次更新: 2024/10/1 19:22:42