1、jar包的导入
- mybatis需要jar包:mybatis-3.4.6.jar
- mysql驱动jar包:mysql-connector-java-5.1.34.-bin.jar
- 日志记录jar包:log4j-1.2.17.jar
2、创建数据库并创建表(mysql)
- 注意数据库表字段命名的规范
3、添加日志配置文件(log4j.properties)
# Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
4、添加mybatis配置文件(mybatis.cfg.xml)
除数据库驱动,url,用户名,密码用自己实际的参数,其他的默认就可以
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<!--数据库驱动-->
<property name="driver" value="com.mysql.jdbc.Driver" />
<!--数据库url-->
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis"></property>
<!--数据库用户名-->
<property name="username" value="root" />
<!--数据库密码-->
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
5、创建与数据库中表相关的实体类(POJO类)
- 注意使用驼峰命名法
6、创建操作数据库的接口方法
package cn.wfq.mybatis.mapper;
import java.util.List;
import cn.wfq.mybatis.model.User;
public interface UserMapper {
/**
* 保存一条用户数据
* @param user
*/
public void saveUser(User user);
/**
* 通过用户id获取一条记录
* @param id
* @return
*/
public User getOneUserById(int id);
/**
* 修改用户数据
* @param user
*/
public void updateUser(User user);
/**
* 根据id删除用户数据
* @param id
*/
public void deleteUser(int id);
/**
* 获取所有用户数据
* @return
*/
public List<User> getAllUser();
}
7、添加操作数据表user的映射文件(userMapper.xml),并在mybatis.cfg.xml中注册
1、添加操作数据表user的映射文件(userMapper.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>标签用来使该xml文件与接口对应,'namespace'属性的参数应该是与xml文件相对应的接口的类路径,本例中就是我们第5步所写的'userMapper'接口-->
<mapper namespace="cn.wfq.mybatis.mapper.UserMapper">
<!--insert、select、update、delete四个标签即代表这增删改查,这里就不解释了 -->
<!--4个标签中的id值要与接口的方法名一一对应,这样执行方法时,就会执行与方法名相同的id中的sql语句,在标签中写入sql语句 -->
<!--#{}这个符号表示要传入的参数,在`{}`中填入参数名 -->
<insert id="saveUser" useGeneratedKeys="true" keyProperty="id">
insert into user(name,age,reg_date) values
(#{name},#{age},#{regDate})
</insert>
<!--resutlType这个属性的参数是返回值类型的全类名 -->
<select id="getOneUserById" resultType="cn.wfq.mybatis.model.User">
select * from user where id = #{id}
</select>
<select id="getAllUser" resultType="cn.wfq.mybatis.model.User">
select * from user
</select>
<update id="updateUser">
update user set
name=#{name},age=#{age},reg_date=#{regDate} where id=#{id}
</update>
<delete id="deleteUser">
delete from user where id = #{id}
</delete>
</mapper>
2、在mybatis.cfg.xml中注册userMapper.xml
<mappers>
<!-- 告知映射文件方式1,一个一个的配置
<mapper resource="cn/wfq/mybatis/mapper/UserMapper.xml" /> -->
<!-- 告知映射文件方式2,自动扫描包内的Mapper接口与配置文件 -->
<package name="cn/wfq/mybatis/mapper" />
</mappers>
8、编写junit测试类
package cn.wfq.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.jupiter.api.Test;
import cn.wfq.mybatis.mapper.UserMapper;
import cn.wfq.mybatis.model.User;
class UserTest {
/**
* 插入数据库测设
* @throws IOException
*/
@Test
void testInsertUser() throws IOException {
//获取配置文件 mybatis.cfg.xml 的输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis.cfg.xml");
//构建 sqlSessionFactory 实例
SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
//获取操作数据库的会话
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = new User("晓东",18,new Date());
try {
userMapper.saveUser(user);
System.out.println(user.toString());
session.commit();
}finally {
session.close();
}
}
/**
* 根据id获取一条数据测试
* @throws IOException
*/
@Test
void testGetOneUserById() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis.cfg.xml");
SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = new User();
try {
user = userMapper.getOneUserById(10004);
System.out.println(user.toString());
session.commit();
}finally {
session.close();
}
}
/**
* 获取所有数据
* @throws IOException
*/
@Test
void testGetAllUser() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis.cfg.xml");
SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User> list = new ArrayList<User>();
try {
list = userMapper.getAllUser();
for (User user : list) {
System.out.println(user.toString());
}
session.commit();
}finally {
session.close();
}
}
/**
* 修改数据
* @throws IOException
*/
@Test
void testUpdateUser() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis.cfg.xml");
SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = new User("晓东",10,new Date());
user.setId(10003);
try {
userMapper.updateUser(user);
System.out.println(user.toString());
session.commit();
}finally {
session.close();
}
}
/**
* 删除数据
* @throws IOException
*/
@Test
void testDeleteUser() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis.cfg.xml");
SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);;
try {
userMapper.deleteUser(10003);
session.commit();
}finally {
session.close();
}
}
}
来源:oschina
链接:https://my.oschina.net/u/4362820/blog/3575053