注解配置SQL映射器(简单的增删改查)

使用注解配置SQL映射器
缺点:方便
优点:不够灵活,不支持所有的功能

第一节:基本映射语句
1,@Insert
2,@Update
3,@Delete
4,@Select
第二节:结果集映射语句
@Results

项目代码:https://download.csdn.net/download/chpllp/10617826

StudentTest.java

package com.java1234.service;

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 StudentTest {
	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 testInsert() {
		logger.info("添加学生");
		Student student = new Student("琪琪", 11);
		studentMapper.insertStudent(student);
		sqlSession.commit();
	}
	
	@Test
	public void testDelete() {
		logger.info("删除学生");
		studentMapper.deleteStudent(6);
		sqlSession.commit();
	}
	
	@Test
	public void testGetById() {
		logger.info("通过ID查找学生");
		Student student = studentMapper.getStudentById(5);
		System.out.println(student.toString());
	}
	
	@Test
	public void testFindStudents() {
		logger.info("查找所有学生");
		List<Student> studentList = studentMapper.findStudents();
		for(Student student:studentList)
		System.out.println(student.toString());
	}
}

StudentMapper.java

package com.java1234.mappers;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.java1234.model.Student;

public interface StudentMapper {
	
	@Insert("insert into t_student values(null, #{name}, #{age})")
	public int insertStudent(Student student);	
	
	@Update("update t_student set name = #{name}, age = #{age} where id = #{id}")
	public int updateStudent(Student student);
	
	@Delete("delete from t_student where id = #{id}")
	public int deleteStudent(int id);
	
	@Select("select * from t_student where id = #{id}")
	public Student getStudentById(Integer id);
	
	@Select("select * from t_student")
	@Results(
			{
				@Result(id=true,column="id",property="id"),
				@Result(column="name",property="name"),
				@Result(column="age",property="age")
			}
	)
	public List<Student> findStudents();
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值