- 配置mybatis
- 编写user.xml
<!--添加用户-->
<insert id="saveUser" parameterType="po.User">
insert into user (username, birthday, sex, address) values (#{userName},#{birthday},#{sex},#{address})
</insert>
3.Dao下编写UserMapper接口
package Dao;
import po.User;
/**
* @description: user dao接口
* @Author: gpc
* @CreateDate: 2019/5/16$ 11:47$
*/
public interface UserMapper {
/**
* 添加用户
*/
public void saveUser(User user);
}
4.编写测试类 test01.java
public void test() throws Exception{
/**
* 测试DAO层
*/
InputStream inputStream = Resources.getResourceAsStream(“mybatis-config.xml”);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Date date = new Date();
User user = new User(“管理员”,“男”,date,“萍乡”);
mapper.saveUser(user);
//提交事务
sqlSession.commit();
sqlSession.close();
}
总结:
1.user.xml的namespace必须是UserMapper
<mapper namespace="Dao.UserMapper">
2.使用getMapper方法
`UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Date date = new Date();
User user = new User("管理员","男",date,"萍乡");
mapper.saveUser(user);
//提交事务
sqlSession.commit();`