标签:
1.添加映射
在映射接口中添加方法如下:
package com.java1234.mappers;
import java.util.List;
import com.java1234.model.Student;
public interface StudentMapper {
public int add(Student student);
public int update(Student student);
public int delete(Integer id);
public Student findStudentByid(Integer id);
public List<Student> find(); }
2.修改映射文件
<?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="com.java1234.mappers.StudentMapper">
<!--定义一个resultmap用来接收所有学生 -->
<resultMap type="Student" id="StudentResult">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
</resultMap>
<insert id="add" parameterType="Student">
insert into t_student values(null,#{name},#{age}) </insert>
<update id="update" parameterType="Student">
update t_student set name=#{name},age=#{age} where id=#{id}
</update>
<delete id="delete" parameterType="Integer">
delete from t_student where id=#{id}
</delete>
<select id="findStudentByid" parameterType="Integer" resultType="Student">
select * from t_student where id=#{id}
</select>
<select id="find" resultMap="StudentResult">
select * from t_student; </select>
</mapper>
3.添加测试 添加jar包
package com.java1234.service;
import static org.junit.Assert.*;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After; import org.junit.Before;
import org.junit.Test; import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;
public class StudentTest2 {
private static Logger logger = Logger.getLogger(StudentTest.class);
private SqlSession sqlSession = null;
private StudentMapper studentMapper = null;
@Before public void setUp() throws Exception {
sqlSession = SqlSessionFactoryUtil.openSession();
studentMapper = sqlSession.getMapper(StudentMapper.class); }
@After public void tearDown() throws Exception { // 方法执行完成后调用关闭
sqlSession.close(); }
@Test public void testAdd() { logger.info("wu1添加成功!");
Student student = new Student("wu1", 30);
studentMapper.add(student); sqlSession.commit(); }
@Test public void testUpdate() { logger.info("wu1修改!");
Student student = new Student(12, "wu2", 88);
studentMapper.update(student);
sqlSession.commit(); }
@Test public void testDelete() { logger.info("删除信息");
studentMapper.delete(11); sqlSession.commit(); }
@Test public void testFindStudentByid() { logger.info("查询byid");
Student s = studentMapper.findStudentByid(13); System.out.println(s); // sqlSession.commit();select不用提交事务 }
@Test public void testFind() { logger.info("查询所有");
List<Student> l = studentMapper.find();
for (Student s : l) { System.out.println(s); } // sqlSession.commit();select不用提交事务 } }
注意在pojo中重写tostring方法 @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; }
标签:
原文地址:http://www.cnblogs.com/pond/p/5297465.html