mybatis有三种映射ORM的方式:纯xml文件映射,基于xml的接口映射以及基于注解的接口映射

以一个例子来说明:这里有一个商品类Product(映射到表product_),类均放在包com.pojo下

Product类
public class Product {

	int id;
	String name;
	float price;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	
	
}
product_表
create table product_(
id int primary key auto_increment,
name varchar(20),
price float
);
纯xml文件映射

首先在项目的src路径下建立文件mybatis-config.xml作为mybatis的映射文件

<?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>
    <typeAliases>
      <package name="com.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8&allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/pojo/Product.xml"/>
    </mappers>
</configuration>

然后在com.pojo包下新建映射文件Product.xml,在文件里定义相关操作的sql语句,ps:记得在mybatis-config.xml文件中配置这个xml文件<mapper resource="com/pojo/Product.xml"/>

Product.xml
<?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.pojo">

	<select id="listProduct" resultType="Product">
		select * from product_
	</select>
	
	<select id="selectOneProduct" parameterType="_int" resultType="Product">
		select * from product_ where id = #{id}
	</select>
	
</mapper>

CRUD操作方法

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
//查询所有商品信息
List<Product> products = session.selectList("listProduct");//参数为Product.xml文件里相应sql语句的id
//查询id为1d的商品信息
Product product = session("selectOneProduct",1);//第二个参数的类型为Product.xml文件里相应sql语句的parameterType
基于xml的接口映射

这种方式是将接口与xml结合起来,创建接口,然后通过xml实现接口,即将接口的具体实现放在xml文件中,而我们不再是直接调用xml文件去操作CRUD,而是通过调用接口的方式访问。参考此处.

首先依旧是在项目的src路径下建立文件mybatis-config.xml映射文件,这一步与纯xml文件映射完全相同。

<?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>
    <typeAliases>
      <package name="com.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8&allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/pojo/ProductMapper.xml"/>
    </mappers>
</configuration>

接着需要创建类的接口,接口放在com.mapper包下

ProductMapper.java
public interface ProductMapper {
	
	List<Product> listProduct();

	Product get(int id);
	
}

然后创建映射文件ProductMapper.xml,放在com.pojo包下

<?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.mapper.ProductMapper">

	<select id="listProduct" resultType="Product">
		select * from product_
	</select>
	
	<select id="get" parameterType="_int" resultType="Product">
		select * from product_ where id = #{id}
	</select>
	
</mapper>

这里有几点是关键,ProductMapper.xml文件里<mapper namespace="com.mapper.ProductMapper">这里namespace属性必须填写所要映射的接口完全限定名;<select id="get" parameterType="_int" resultType="Product">这一句的id相当于接口的某个函数的方法体,id属性对应接口中的方法名,parameterType属性对应方法的参数类型,resultType属性对应方法的返回值类型。
最后别忘了在mybatis-config.xml文件中配置ProductMapper.xml<mapper resource="com/pojo/ProductMapper.xml"/>

CRUD操作方法

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();

//获得一个ProductMapper实例
ProductMapper productMapper = session.getMapper(ProductMapper.class);

//查询所有商品信息
List<Product> products = productMapper.listProduct();
//查询id为1d的商品信息
Product product = productMapper.get(1);
基于注解的接口映射

这种方式将不再需要创建除了mybatis-config.xml之外的映射文件,采用接口调用的方式操作CRUD

首先依旧是在项目的src路径下建立文件mybatis-config.xml映射文件

<?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>
    <typeAliases>
      <package name="com.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8&allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="com.mapper.ProductMapper"/>
    </mappers>
</configuration>

接着创建接口ProductMapper.java

@Mapper
public interface ProductMapper {
	
	@Select("select * from product_")
	List<Product> listProduct();

	@Select("select * from product_ where id=#{id}")
	Product get(int id);
	
}

最后记得在mybatis-config.xml文件中配置接口ProductMapper<mapper class="com.mapper.ProductMapper"/>或者<package name ="com.mapper" />

CRUD操作方法

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();

//获得一个ProductMapper实例
ProductMapper productMapper = session.getMapper(ProductMapper.class);

//查询所有商品信息
List<Product> products = productMapper.listProduct();
//查询id为1d的商品信息
Product product = productMapper.get(1);