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)
);
<?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檔案,方便以後使用)
<?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>
<?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.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://自己的伺服器ip或localhost:3306/要連線的資料庫名稱?useUnicode=true&characterEncoding=utf8
jdbc.username=XXXX
jdbc.password=YYYY
<?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>
<?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>
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() {
}
}
package com.example.mapper;
import com.example.pojo.User;
/**
* 資料存取層的介面
*/
public interface UserMapper {
int insert(User user);
}
<?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>
package com.example.service;
import com.example.pojo.User;
/**
* 業務邏輯層介面
*/
public interface UserService {
int insert(User user);
}
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