上午参考了一些文章,整合了spring+mybatis,现在共享一下。把代码帖出来,如果有什么疑问,到mybatis官网下载相关文档来看一下就可以了。如果没有基础,请看我之前发的文章。
1.实体bean
package org.hyn.bean;
public class User {
private int id;
private String name;
private int age;
...//长长的set get 方法
2.Mapper及配置文件
package org.hyn.maper;
import org.hyn.bean.User;
public interface UserMapper {
public void insertUser(User user);
public User getUser(String name);
}
<?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="org.hyn.maper.UserMapper">
<insert id="insertUser" parameterType="org.hyn.bean.User">
insert into user(name,age) values(#{name},#{age})
</insert>
<select id="getUser" resultType="org.hyn.bean.User"
parameterType="java.lang.String">
select * from user where name=#{name}
</select>
<!-- 当使用该Mybatis与Spring整合的时候,该文件必须和相应的Mapper接口文件同名,并在同一路径下 -->
</mapper>
3.spring配置文件
4.测试类
@Test
public void testGetUser() {
ApplicationContext aContext = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
UserMapper userMapper = aContext.getBean(UserMapper.class);
User user = userMapper.getUser("张三");
System.out.println(user.toString());
}
@Test
public void testAddUser(){
ApplicationContext aContext = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
UserMapper userMapper = aContext.getBean(UserMapper.class);
User user = new User();
user.setName("张三");
user.setAge(18);
userMapper.insertUser(user);
System.out.println("添加成功");
}