mybatis的概述
mybatis是一个持久层框架,用java编写的。
它封装了jdbc操作的很多细节,使开发者只需要关注sql语句本身,而无需关注注册驱动,创建连接等繁杂过程
它使用了ORM思想实现了结果集
ORM:Object Relational Mappging 对象关系映射
简单的说:
就是把数据库表和实体类及实体类的属性对应起来
让我们可以操作实体类就实现操作数据库表。
Mybatis环境搭建
• 创建maven工程并导入坐标
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency>
创建实体类和dao的接口
在bean.xml中整合MyBatis框架
<!-- Spring整合MyBatis框架--><!-- 配置连接池--><beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"><propertyname="driverClass"value="com.mysql.jdbc.Driver"></property><propertyname="jdbcUrl"value="jdbc:mysql://localhost/yoshop"></property><propertyname="user"value="root"></property><propertyname="password"value="064530"></property></bean><!-- 配置SqlSessionFactory工厂--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"></property></bean><!-- 配置AccountDao接口所在包--><beanid="mapperScanner"class="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="basePackage"value="com.yoshop.dao"></property></bean>
property,参数注入 ,对应于bean类公开的JavaBean setter方法。
注解完成一对一 一对多
package com.cr.mapper;import org.apache.ibatis.annotations.Many;import org.apache.ibatis.annotations.One;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.mapping.FetchType;import com.cr.pojo.User;publicinterfaceUserMapper{//one to one@Select("select * from user where userId = #{userId}")@Results({@Result(id=true,column="userId",property="userId"),//user表中的属性(必须标记id,其他属性可以不写)@Result(column="userName",property="userName"),@Result(column="userPassword",property="userPassword"),@Result(column="userAge",property="userAge"),@Result(column="userEmail",property="userEmail"),@Result(column="userId",property="userAddress",one=@One(select="com.cr.mapper.AddressMapper.getAddressByUserId",fetchType= FetchType.EAGER))})public UsergetUserById(int userId);//one to many@Select("select * from user where userId=#{userId}")@Results({@Result(id=true,column="userId",property="userId"),@Result(column="userName",property="userName"),@Result(column="userPassword",property="userPassword"),@Result(column="userAge",property="userAge"),@Result(column="userEmail",property="userEmail"),@Result(column="userId",property="books",many=@Many(select="com.cr.mapper.BookMapper.getBooksByUserId",fetchType= FetchType.EAGER))})public UsergetUserAndBooksById(int userId);}
package com.cr.mapper;import org.apache.ibatis.annotations.Select;import com.cr.pojo.Address;publicinterfaceAddressMapper{@Select("select * from address where userId=#{userId}")public AddressgetAddressByUserId(int userId);}
package com.cr.mapper;import java.util.List;import org.apache.ibatis.annotations.Select;import com.cr.pojo.Book;publicinterfaceBookMapper{@Select("select * from book where userId = #{userId}")public List<Book>getBooksByUserId(int userId);}
privatestaticvoidprintUser(User user){
System.out.println("用户id:"+user.getUserId()+"\n姓名:"+user.getUserName()+"\n年龄:"+user.getUserAge()+"\n邮箱:"+user.getUserEmail()+"\n地址:"+user.getAddress().toString());}
package com.cr.mapper;import java.util.List;import org.apache.ibatis.annotations.Select;import com.cr.pojo.Book;publicinterfaceBookMapper{@Select("select * from book where userId = #{userId}")public List<Book>getBooksByUserId(int userId);}
privatestaticvoidprintUserAndBooks(User user){
System.out.println("用户id:"+user.getUserId()+"\n姓名:"+user.getUserName()+"\n年龄:"+user.getUserAge()+"\n邮箱:"+user.getUserEmail());
List<Book> books= user.getBooks();
String messsage="喜欢的书籍:";for(Book book:books){
messsage= messsage+book.getBookName()+" ";}
System.out.println(messsage);}
privatestaticvoidprintUserAndBooks(User user){
System.out.println("用户id:"+user.getUserId()+"\n姓名:"+user.getUserName()+"\n年龄:"+user.getUserAge()+"\n邮箱:"+user.getUserEmail());
List<Book> books= user.getBooks();
String messsage="喜欢的书籍:";for(Book book:books){
messsage= messsage+book.getBookName()+" ";}
System.out.println(messsage);}
写在这段后
一对一 要把另一个实体类当做对象作为第一个的实体类的对象,查询到的address信息,直接被封装到了user实体类的 address属性中,该属性是一个address类型的对象,记得给address实体类 toString方法
一对多也要把另一个实体类当做对象集合作为另一个实体类的属性,查询到的都会自动注入到user对象里
多对多
@Results与 @Result的使用
@Results是最简单的映射,指定@Result将基本数据库表字段,装配到实体类属性的映射。
column是数据库表的列名
property实体的字段
id为是否为主键。
实体字段 表的列名
sid stuid
sname stuname
gid gid
grade grade
简单介绍一些注解
@ResultMap的用法。
当这段@Results代码需要在多个方法用到时,为了提高代码复用性,我们可以为这个@Results注解设置id,然后使用@ResultMap注解来复用这段代码。
@One的用法。
当我们需要通过查询到的一个字段值作为参数,去执行另外一个方法来查询关联的内容,而且两者是一对一关系时,可以使用@One注解来便捷的实现。比如当我们需要查询学生信息以及其所属班级信息时,需要以查询到的class_id为参数,来执行ClassesMapper中的selectById方法,从而获得学生所属的班级信息。
@Many的用法。
与@One类似,只不过如果使用@One查询到的结果是多行,会抛出TooManyResultException异常,这种时候应该使用的是@Many注解,实现一对多的查询。
一对一关联
IEmployeeDao.java
package com.mybatisstudy.dao;import java.util.HashMap;import java.util.List;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.mapping.FetchType;import org.apache.ibatis.annotations.One;import com.mybatisstudy.model.Employee;publicinterfaceIEmployeeDao{/*fetchType=FetchType.EAGER,如果是EAGER,那么表示取出这条数据时,它关联的数据也同时取出放入内存中,如果是LAZY那么取出这条数据时,它关联的数据并不取出来
在同一个session中,什么时候要用,就什么时候取(再次访问数据库)。
但是,在session外,就不能再取了。用EAGER时,因为在内存里,所以在session外也可以取。*/@Results({@Result(column="empId",property="empId",id=true),//id=true,表示为主键@Result(column="empName",property="empName"),@Result(column="empBirthDay",property="empBirthDay"),@Result(column="empSex",property="empSex"),@Result(column="deptId",property="dept",one=@One(select="com.mybatisstudy.dao.IDepartmentDao.selectDeptById",fetchType=FetchType.EAGER))})@Select("SELECT * FROM tb_emp WHERE empBirthDay between #{startTime} and #{endTime} ;")public List<Employee>selectEmpsByYears(HashMap<String,Object> argMap);}
IDepartmentDao.java
package com.mybatisstudy.dao;import java.util.List;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import com.mybatisstudy.model.Department;publicinterfaceIDepartmentDao{@Results({@Result(column="deptId",property="deptId",id=true),@Result(column="deptName",property="deptName")})@Select(" SELECT * FROM tb_dept d WHERE d.deptId=#{deptId};")public DepartmentselectDeptById(int deptId);}
多对多关联
IGoodsDao.java
package com.mybatisstudy.dao;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.mapping.FetchType;import org.apache.ibatis.annotations.Many;import com.mybatisstudy.model.Goods;publicinterfaceIGoodsDao{//根据goodsId得到商品@Results({@Result(id=true,column="goodsId",property="goodsId"),@Result(column="name",property="name"),@Result(column="price",property="price"),@Result(column="goodsId",property="orders",many=@Many(select="com.mybatisstudy.dao.IOrderDao.getAllOrderByGoodsId",fetchType=FetchType.LAZY)),})@Select("SELECT * FROM tb_goods WHERE goodsId=#{goodsId};")public GoodsgetGoodsById(int goodsId);}
IOrderDao.java
package com.mybatisstudy.dao;import java.util.List;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import com.mybatisstudy.model.Order;publicinterfaceIOrderDao{//根据商品的id,去查找所有相关的订单@Results({@Result(id=true,column="orderId",property="orderId"),@Result(column="total",property="total"),@Result(column="orderDate",property="orderDate")})@Select("SELECT * FROM tb_order WHERE orderId in(SELECT orderId FROM tb_goods_order WHERE goodsId=#{goodsId})")public List<Order>getAllOrderByGoodsId(int goodsId);}