原文:https://www.cnblogs.com/benjieqiang/p/11183580.html
一些基础问题的解决
用Maven创建的项目:https://www.cnblogs.com/guxingy/p/13441594.html
idea创建SqlMapConfig.xml:https://www.cnblogs.com/guxingy/p/13444274.html
idea创建log4j.properties:https://www.cnblogs.com/guxingy/p/13444342.html
idea创建User.xml:https://www.cnblogs.com/guxingy/p/13444381.html
idea执行单个测试方法:https://www.cnblogs.com/guxingy/p/13444632.html
数据库对应的表
初始数据
项目结构
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>test1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
User.java
package com.example.test1;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
}
}
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
# 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
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>
<!-- 配置环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置连接池-->
<dataSource type="POOLED">
<!--配置连接数据库的4个基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<mapper resource="User.xml"/>
</mappers>
</configuration>
User.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">
<!--namespace:用来区别不同的类的名字 -->
<mapper namespace="User">
<!-- 通过Id查询一个用户 -->
<select id="findUserById" parameterType="Integer" resultType="com.example.test1.User">
select * from user where id = #{v}
</select>
<!-- 根据用户名模糊查询用户列表 -->
<select id="findUserByUsername" parameterType="String" resultType="com.example.test1.User">
select * from user where username like CONCAT('%',#{username},'%')
</select>
<!-- 添加用户 -->
<insert id="insertUser" parameterType="com.example.test1.User">
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
insert into user (username,birthday,address,sex) values(#{username},#{birthday},#{address},#{sex})
</insert>
<!-- 更新用户 -->
<update id="updateUserById" parameterType="com.example.test1.User">
update user
set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}
where id = #{id}
</update>
<!-- 删除用户 -->
<delete id="deleteUserById" parameterType="Integer">
delete from user
where id = #{vvvvv}
</delete>
</mapper>
MybatisTest.java
import com.example.test1.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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
/**
* @ClassName: MybatisTest
* @author: benjamin
* @version: 1.0
* @description: TODO
* @createTime: 2019/07/13/11:50
*/
public class MybatisTest {
public static void main(String[] args) {
}
//通过Id查询一个用户
@Test
public void testSearchById() throws IOException {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = sqlSessionFactory.openSession();
//4.执行Sql语句
User user = session.selectOne("User.findUserById", 1);
//5. 打印结果
System.out.println(user);
//6.释放资源
session.close();
in.close();
}
//根据用户名模糊查询用户列表
@Test
public void testFindUserByUsername() throws IOException {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = sqlSessionFactory.openSession();
//4.执行Sql语句
List<User> list = session.selectList("User.findUserByUsername", "测试");
//5. 打印结果
for (User user:list) {
System.out.println(user);
}
//6.释放资源
session.close();
in.close();
}
//添加用户
@Test
public void testInsertUser() throws IOException {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.执行Sql语句
User user = new User();
user.setUsername("小强");
user.setBirthday(new Date());
user.setAddress("广州");
user.setSex("男");
int i = sqlSession.insert("User.insertUser", user);
sqlSession.commit();
//5. 打印结果
// 刚保存用户,此时用户ID需要返回。执行完上面insert程序后,此时就能知道用户的ID是多少
// 需要在User.xml文件中配置
System.out.println("插入id:"+user.getId());//插入id:30
//6.释放资源
sqlSession.close();
in.close();
}
//更新用户
@Test
public void testUpdateUserById() throws IOException {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.执行Sql语句
User user = new User();
user.setId(3);
user.setUsername("小李");
user.setBirthday(new Date());
user.setAddress("深圳");
user.setSex("女");
int i = sqlSession.insert("User.updateUserById", user);
sqlSession.commit();
//5. 打印结果
System.out.println(user.getId());
//6.释放资源
sqlSession.close();
in.close();
}
//删除用户
@Test
public void testDeleteUserById() throws IOException {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.执行Sql语句
int i = sqlSession.insert("User.deleteUserById", 3);
sqlSession.commit();
//5. 打印结果
System.out.println(i);
//6.释放资源
sqlSession.close();
in.close();
}
}