mybatis 使用注解简化xml映射文件

目录


关于mybatis注解

初次简单使用mybatis注解示例

利用注解实现指定映射

使用注解实现表间关联(1对1)

 

 


 

 

 

关于mybatis注解

  注解在java中特别常见,mybatis中也支持注解。

  mybatis的注解主要功能是:简化mapper.xml文件,简单的sql可以使用注解,而不用在取mapper.xml中写sql了,但是动态sql或者稍微复杂的sql,还得写在mapper.xml中。

  mybatis的注解和mapper.xml可以共存。

  需要注意:

  mybatis配置文件在加载映射文件或者接口的时候,是有点区别的。

  1、对于xml文件,可以使用:

<mapper resource="cn/ganlixin/mapper/XxxMapper.xml" />
<mapper url="file:///E:/mappers/XxxMapper.xml" />

  2、对于interface,可以使用:

<mapper class="cn.ganlixin.mapper.PersonMapper" />
<package name="cn.ganlixin.mapper" />

  

 

初次简单使用mybatis注解示例

  创建实体类:cn.ganlixin.pojo.Person.java

package cn.ganlixin.pojo;

import java.io.Serializable;

public class Person implements Serializable{
	private int id;
	private String name;
	private int age;
	//省略了无参构造方法、有参构造方法、setter、getter、toString
}

  

  创建interface:cn.ganlixin.mapper.PersonMapper.java

package cn.ganlixin.mapper;

import java.util.List;

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

import cn.ganlixin.pojo.Person;

public interface PersonMapper {
	
	@Select("select * from person where id=#{0}")
	public Person selectPersonById(int id);
	
	@Select("select * from person")
	public List<Person> selectAllPerson();
	
	@Delete("delete from person where id=#{id}")	
	public int deleteOnePerson(Person person);
	
	@Insert("insert into person (id, name, age) values (default, #{name}, #{age})")
	public int addPerson(Person person);
	
	@Update("update person set name=#{name} where id=#{id}")
	public int updatePersonName(Person person);
}

  

  修改mybatis配置文件,加载该interface:

<?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 resource="conf/db.properties"></properties>

	<settings>
		<setting name="logImpl" value="log4J"></setting>
	</settings>

	<typeAliases>
		<package name="cn.ganlixin.pojo" />
	</typeAliases>

	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="${driver}"></property>
				<property name="url" value="${url}"></property>
				<property name="username" value="${username}"></property>
				<property name="password" value="${password}"></property>
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<!-- 一次只加载一个interface -->
		<!-- <mapper class="cn.ganlixin.mapper.PersonMapper"></mapper> -->
		
		<!-- 一次性加载包下的所有interface -->
		<package name="cn.ganlixin.mapper"></package>
	</mappers>
</configuration>

  

  进行测试:

package cn.ganlixin.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.ganlixin.mapper.PersonMapper;
import cn.ganlixin.pojo.Person;

public class TestMybatis {
	public static void main(String[] args) {

		try {
			String resource = "conf/mybatis.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			SqlSession session = sqlSessionFactory.openSession();

			PersonMapper mapper = session.getMapper(PersonMapper.class);

			Person person = mapper.selectPersonById(1);
			System.out.println(person);
			//----------------------------------------------------
			
			List<Person> list = mapper.selectAllPerson();
			for (Person p : list) {
				System.out.println(p);
			}
			//----------------------------------------------------
			
			int count = mapper.addPerson(new Person(3, "cccc", 55));
			System.out.println(count);
			//----------------------------------------------------
			
			Person p = new Person();
			p.setId(3);
			p.setName("dddd");
			count = mapper.updatePersonName(p);
			System.out.println(count);
			//----------------------------------------------------
			
			count = mapper.deleteOnePerson(p);
			System.out.println(count);
			//----------------------------------------------------
			
			session.commit();
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

  

 

利用注解实现指定映射

  假设上面的Person实体类中的属性名与数据库中person表中字段名不一一对应时,比如下面这样:

package cn.ganlixin.pojo;

import java.io.Serializable;

public class Person implements Serializable{
	private int id1;
	private String name1;
	private int age1;
	//省略了无参构造方法、有参构造方法、setter、getter、toString
}

  数据库中person表中的字段是id、name、age,显然与Person类的id1、name1、age1属性不符合。

 

  重新修改PersonMapper接口:

package cn.ganlixin.mapper;

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 cn.ganlixin.pojo.Person;

public interface PersonMapper {
	@Results(value={
		@Result(id=true, column="id", property="id1"),
		@Result(column="name", property="name1"),
		@Result(column="age", property="age1")
	})
	@Select("select * from person where id=#{0}")
	public Person selectPersonById(int id);
	
	// 需要多次配置@Results
	@Results(value={
		@Result(id=true, column="id", property="id1"),
		@Result(column="name", property="name1"),
		@Result(column="age", property="age1")
	})
	@Select("select * from person")
	public List<Person> selectAllPerson();
	
	// 对于增删改,属性作为参数时,传入的参数直接指定准确的属性名,不要用@Result
	@Delete("delete from person where id=#{id1}")	
	public int deleteOnePerson(Person person);
	
	@Insert("insert into person (id, name, age) values (default, #{name1}, #{age1})")
	public int addPerson(Person person);
	
	@Update("update person set name=#{name} where id=#{id1}")
	public int updatePersonName(Person person);
}

  

  进行测试:

  测试代码与上一次的测试代码相同,并且测试结果也与上一次的测试结果相同。

 

 

使用注解实现表间关联(1对1)

  1对1,就以独生子为例吧,一个father只有一个son。

 

  创建实体类cn.ganlixin.pojo.Son.java

package cn.ganlixin.pojo;

public class Son {
	private int id;
	private String name;
	
	private int fid; // father id
	
	//省略了无参构造方法、有参构造方法、setter、getter、toString	
}

  

  创建实体类cn.ganlixin.pojo.Father.java

package cn.ganlixin.pojo;

public class Father {
	private int id;
	private String name;
	private Son son;  // 包含一个son对象

	//省略了无参构造方法、有参构造方法、setter、getter、toString
}

  

  创建cn.ganlixin.mapper.FatherMapper.java

package cn.ganlixin.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import cn.ganlixin.pojo.Father;

public interface FatherMapper {
	
	@Select("select f.id, f.name, s.id `son.id`, s.name `son.name`, s.fid `son.fid` "
			+ "from father f left join son s on f.id=s.fid")
	public List<Father> selectAll();
}

  

 

posted @ 2018-12-18 16:18  寻觅beyond  阅读(517)  评论(0编辑  收藏  举报
返回顶部