SM整合步骤
预期项目结构
新建数据库和数据表
- springuser.sql脚本如下
create database ssm;
use ssm;
create table users(
userid int primary key,
uname varchar(20),
upass varchar(20)
);
create table accounts(
aid int primary key,
aname varchar(20),
acontent varchar(50)
);
新建项目
- 新建maven项目
- 选择quickstart模板
- 修改项目目录,删除自动生成的类和对应测试类
修改pom.xml文件
- 添加相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>ch09-spring-sm</artifactId>
<version>1.0.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- 添加单元测试的依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- 添加spring-context依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.22</version>
</dependency>
<!-- 添加spring-aspects依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.22</version>
</dependency>
<!-- 添加spring-tx依赖,用于事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.22</version>
</dependency>
<!-- 添加spring-jdbc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.22</version>
</dependency>
<!-- 添加mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- 添加mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 添加mybatis和spring的整合依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!-- 添加数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.11</version>
</dependency>
</dependencies>
<build>
<!-- 添加资源文件指定 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
添加模板文件
分别添加MyBatis相应配置文件的模板(SqlMapConfig.xml和XXXXMapper.xml文件,方便以后使用)
- 如何添加模板文件
- 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>
<properties resource="db.properties"></properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.example.pojo"></package>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://ip:port/dataBaseName?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"/>
<property name="username" value="userName"/>
<property name="password" value="passWord"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name=""></package>
</mappers>
</configuration>
- XXXXMapper.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="">
</mapper>
jdbc.properties
- 添加jdbc.properties文件至src/main/resources目录下
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://自己的服务器ip或localhost:3306/要连接的数据库名称?useUnicode=true&characterEncoding=utf8
jdbc.username=XXXX
jdbc.password=YYYY
SqlMapConfig.xml
- 添加SqlMapConfig.xml文件至src/main/resources目录下:选择我们自己添加的模板文件(该状态下idea无法电脑截图,手机拍摄,包涵包涵)
Spring核心配置文件
- 由于分层开发,需要添加两个配置文件:applicationContext_mapper.xml和applicationContext_service.xml。添加操作见下
- applicationContext_mapper.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 读取数据库连接文件 jdbc.properties -->
<context:property-placeholder location="jdbc.properties"/>
<!-- 创建数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置SqlSessionFactoryBean类 -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBatis的核心配置文件 -->
<property name="configLocation" value="SqlMapConfig.xml"/>
<!-- 注册实体类的别名 -->
<property name="typeAliasesPackage" value="com.example.pojo"/>
</bean>
<!-- 注册mapper.xml文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
</beans>
- applicationContext_service.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 导入applicationContext_mapper.xml文件-->
<import resource="applicationContext_mapper.xml"/>
<!-- sm框架是基于注解开发的,要添加包扫描 -->
<context:component-scan base-package="com.example.service.impl"/>
<!-- 添加事务处理,此时先不管-->
</beans>
添加实体类
- 依据users数据表的字段,创建User实体类
package com.example.pojo;
public class User {
private Integer userid;
private String uname;
private String upass;
@Override
public String toString() {
return "User{" +
"userid=" + userid +
", uname='" + uname + '\'' +
", upass='" + upass + '\'' +
'}';
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public User(String uname, String upass) {
this.uname = uname;
this.upass = upass;
}
public User(Integer userid, String uname, String upass) {
this.userid = userid;
this.uname = uname;
this.upass = upass;
}
public User() {
}
}
数据访问层
- 添加UserMapper接口
package com.example.mapper;
import com.example.pojo.User;
/**
* 数据访问层的接口
*/
public interface UserMapper {
int insert(User user);
}
- 添加UserMapper.xml,先选择我们自己添加的XXXMapper.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.example.mapper.UserMapper">
<!--
int insert(User user);
private Integer userid;
private String uname;
private String upass;
-->
<insert id="insert" parameterType="user">
insert into users values (#{userid}, #{uname}, #{upass})
</insert>
</mapper>
业务逻辑层
- 添加UserService接口
package com.example.service;
import com.example.pojo.User;
/**
* 业务逻辑层接口
*/
public interface UserService {
int insert(User user);
}
- 添加UserServiceImpl实现类
package com.example.service.impl;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 业务实现类
*/
@Service
public class UserServiceImpl implements UserService {
//业务逻辑层实现类持有数据访问层的接口类型的变量
@Autowired
UserMapper userMapper;
@Override
public int insert(User user) {
return userMapper.insert(user);
}
}
测试
package com.example.test;
import com.example.pojo.User;
import com.example.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestUserInsert {
//测试用户信息导入
@Test
public void testUserInsert(){
//创建Spring容器并启动
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_service.xml");
//获取业务逻辑实现类的对象
UserService userService = (UserService) ac.getBean("userServiceImpl");
//调用业务功能
int num = userService.insert(new User(1, "王小涵", "hanzhanghan"));
if(num == 1){
System.out.println("用户信息导入成功!");
}else{
System.out.println("用户信息导入失败!");
}
}
}
测试输出
- 控制台输出
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@475835b1] was not registered for synchronization because synchronization is not active
Aug 28, 2022 10:31:31 AM com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
INFO: {dataSource-1} inited
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4d4d8fcf] will not be managed by Spring
==> Preparing: insert into users values (?, ?, ?)
==> Parameters: 1(Integer), 王小涵(String), hanzhanghan(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@475835b1]
用户信息导入成功!
Process finished with exit code 0
- 数据表变化
相关文章
暂无评论...