1. 新建maven项目
导入依赖
在porn.xml中写入依赖
<!--mybatis坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<!--单元测试坐标-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
?
2. 创建user数据表
?
?
3. 编写User实体类
?
?4. 编写UserMapper
public interface UserMapper {
@Insert("insert into user values (#{id},#{username},#{password}")
public void save(User user);
@Update("update user set username=#{username},password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int id);
@Select("select * from user where id=#{id}")
public User findById(int id);
@Select("select * from user")
public List<User> findAll();
}
?
5. 编写核心文件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便签加载外部的properties文件-->
<properties resource="jdbc.properties"></properties>
<!--数据源环境-->
<environments default="developement">
<environment id="developement">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射关系-->
<mappers>
<!--指定接口所在的包-->
<package name="com.demo.mapper"/>
</mappers>
</configuration>
?
6. 编写jdbc.properties
?
?
7. 编写测试类
public class MybatisTest {
private UserMapper mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = build.openSession(true);
mapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testSave(){
User user = new User();
user.setUsername("tom");
user.setPassword("123");
mapper.save(user);
}
@Test
public void testUpdate(){
User user = new User();
user.setId(10);
user.setUsername("tom123");
user.setPassword("321");
mapper.update(user);
}
@Test
public void testDelete(){
User user = new User();
mapper.delete(10);
}
@Test
public void testFindById(){
User user = mapper.findById(2);
System.out.println(user);
}
@Test
public void testFindAll(){
List<User> all = mapper.findAll();
for (User user : all) {
System.out.println(user);
}
}
}
|