mybatis
持久层框架
MyBatis是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架
MyBatis消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索
MyBatis使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs
(Plan Old Java Objects,普通的 Java对象)映射成数据库中的记录。
跟hibernate相比,我们还需要写sql,它介于hibernate和jdbc之间的框架
======================================================
总配置文件
在src根目录中 MyBatis配置文件mybatis.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> <!-- 配置的别名,在下面的xml中书写简单 --> <typeAliases> <typeAlias type="com.kaishengit.pojo.Admin" alias="Admin"/> <typeAlias type="com.kaishengit.pojo.Post" alias="Post"/> </typeAliases> <!-- environments中可以有多个environment,每个environment设置一个id,分别表示开发,测试,上线等等 要使用哪个environment就default="xxx" --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <!-- 它自己提供数据源,不需要dbcp啊c3p0啊什么的 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///book"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 声明写的其他的配置文件 --> <mappers> <mapper resource="com/kaishengit/mapper/AdminMapper.xml"/> <mapper resource="com/kaishengit/mapper/PostMapper.xml"/> </mappers> </configuration>
==============================================================
==============================================================
写AdminMapper.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"> <!-- 当前写的xml的完全限定名 以类的形式表示,这个xml文件类似与以前的dao --> <mapper namespace="com.kaishengit.mapper.AdminMapper"> <!--insert方法 id表示方法名 --> <insert id="save" parameterType="Admin"> insert into admin(name,password) values("tom","123") </insert> <!-- 参数类型(传进来的id)parameterType="int" 返回类型resultType="com.kaishengit.pojo.Admin" --> <select id="findById" parameterType="int" resultType="com.kaishengit.pojo.Admin"> select * from admin where id = #{id} </select> <!-- resultType:迒回值类型,如果是自己定义的Entity,需要在mybatis.xml中中配置别名。 --> <typeAliases> <typeAlias type="com.kaishengit.mybatis.entity.User" alias="User"/> </typeAliases> <!-- 这样就可以写resultType="Admin" --> </mapper>
举例
import java.io.Reader; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Test { public static void main(String[] args) throws Exception { /* 1. 构建SqlSessionFactory对象 提供一个reader供读取xml文件*/ Reader reader = Resources.getResourceAsReader("mybatis.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); /* 2.创建SqlSession对象 */ /* SqlSession session = sessionFactory.openSession();*/ // 自动提交,下面就不用写session.commit(); SqlSession session = sessionFactory.openSession(true); /*******************************************************/ //数据库操作都写在这里 //添加 session.insert("com.kaishengit.mapper.AdminMapper.save"); // id查询 Admin admin = (Admin) session.selectOne("com.kaishengit.mapper.AdminMapper.findById", 1); /******************************************************/ //记得要提交和关闭 // session.commit(); session.close(); } }
------------------------------------------------------------------------
------------------------------------------------------------------------
------------------------------------------------------------------------
形式2:接口的形式
总配置文件
在src根目录中 MyBatis配置文件mybatis.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> <!-- 配置的别名,在下面的xml中书写简单 --> <typeAliases> <typeAlias type="com.kaishengit.pojo.Admin" alias="Admin"/> <typeAlias type="com.kaishengit.pojo.Post" alias="Post"/> </typeAliases> <!-- environments中可以有多个environment,每个environment设置一个id,分别表示开发,测试,上线等等 要使用哪个environment就default="xxx" --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <!-- 它自己提供数据源,不需要dbcp啊c3p0啊什么的 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///book"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 声明写的其他的配置文件 --> <mappers> <mapper resource="com/kaishengit/mapper/AdminMapper.xml"/> <mapper resource="com/kaishengit/mapper/PostMapper.xml"/> </mappers> </configuration>
写AdminMapper.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"> <!-- 当前写的AdminMapper接口的完全限定名 --> <mapper namespace="com.kaishengit.mapper.AdminMapper"> <!--insert方法 id表示方法名 --> <insert id="save" parameterType="Admin"> insert into admin(name,password) values(#{name},#{password}) </insert> <update id="update" parameterType="Admin"> update admin set name = #{name},password=#{password} where id = #{id} </update> <delete id="delete" parameterType="int"> delete from admin where id = #{id} </delete> <!-- 参数类型(传进来的id)parameterType="int" 返回类型resultType="com.kaishengit.pojo.Admin" --> <select id="findById" parameterType="int" resultType="com.kaishengit.pojo.Admin"> select * from admin where id = #{id} </select> <!-- 设置resultType="list"表示返回的是一个list数组,但是在程序中接收的时候 list<Admin>是不知道返回的list里面是admin的是Oblect对象,所以需要设置resultMap="adminMap" 然后设置一个节点resultMap--> <select id="findAll" resultType="list" resultMap="adminMap"> select * from admin </select> <!-- 设置这个封装成Admin.相当于以前的rowMapper,都是进行封装 --> <resultMap type="Admin" id="adminMap"> <!-- property属性名 column列名--> <id property="id" column="id"/> <result property="name" column="name"/> <result property="password" column="password"/> </resultMap> <select id="findByName" parameterType="String" resultType="Admin"> select * from admin where name = #{name} </select> <!-- parameterType="map"多个查询的时候,参数必须封装成对象后者map --> <select id="findByNameAndPassword" parameterType="map" resultType="Admin"> select * from admin where name = #{name} and password = #{password} </select> <!-- 如果是多表查询,例如 public class Admin { private Integer id; private String name; private String password; private List<Post> posts; } public class Post { private Integer id; private String title; private Admin admin; }--> <!-- 那么对于mybatis是不会像hibernate那样自动去查的,sql必须重写 --> <!-- 因为是一对多,一个admin会对应多个post,resultMap="adminPostMap" --> <select id="findById" parameterType="int" resultType="Admin" resultMap="adminPostMap"> SELECT admin.id,NAME,PASSWORD,post.id AS pid,title,aid FROM admin INNER JOIN post ON admin.id = post.aid WHERE admin.id = #{id} </select> <!-- 设置这个封装成Admin.相当于以前的rowMapper,都是进行封装 --> <resultMap type="Admin" id="adminPostMap"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="password" column="password"/> <!-- admin中属性名property="posts" posts集合中都是post 类名ofType="Post" --> <collection property="posts" ofType="Post"> <!-- 对于post里面的id不能和admin的id重复,改成pid,那么在sql语句中要设置别名 --> <id property="id" column="pid"/> <result property="title" column="title"/> </collection> </resultMap> </mapper>
举例
写一个接口AdminMapper要和AdminMapper.xml相对应
import java.util.List; import java.util.Map; import com.kaishengit.pojo.Admin; public interface AdminMapper { // save()方法,要和xml中的save相对应 public void save(Admin admin); public Admin findById(int id); public void update(Admin admin); public void delete(int id); public List<Admin> findAll(); public Admin findByName(String name); public Admin findByNameAndPassword(Map<String, Object> param); }
import java.io.Reader; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Test { public static void main(String[] args) throws Exception { /* 1. 构建SqlSessionFactory对象 提供一个reader供读取xml文件*/ Reader reader = Resources.getResourceAsReader("mybatis.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //2.创建SqlSession对象 /* SqlSession session = sessionFactory.openSession(); */ // 自动提交,下面就不用写session.commit(); SqlSession session = sessionFactory.openSession(true); /******************************************************/ // 数据库操作都写在这里 // 创建实现接口的对象 AdminMapper mapper = session.getMapper(AdminMapper.class); // 添加 Admin admin = new Admin(); admin.setName("iBatis"); admin.setPassword("888888"); mapper.save(admin); // 修改 Admin admin = mapper.findById(3); admin.setName("tom"); mapper.update(admin); //删除 mapper.delete(4); // 查询 Admin admin = mapper.findById(1); System.out.println(admin.getName()); System.out.println(admin.getPassword()); // 查询所有 List<Admin> adminList = mapper.findAll(); System.out.println(adminList.size()); for(Admin a : adminList) { System.out.println(a.getName()); } //根据名字查 Admin admin = apper.findByName("tom"); System.out.println(admin.getName()); System.out.println(admin.getPassword()); /*根据多个属性查询 因为在xml中只能接受一个参数类型,所以传过去多个参数的时候,只能封装成对象或者map */ Map<String, Object> param = new HashMap<String, Object>(); param.put("name", "tom"); param.put("password", "000000"); Admin admin =mapper.findByNameAndPassword(param); System.out.println(admin.getName()); System.out.println(admin.getPassword()); // 多表查询 查询admin admin中有多个post Admin admin = mapper.findById(1); System.out.println(admin.getName()); System.out.println(admin.getPassword()); List<Post> postList = admin.getPosts(); for(Post p : postList) { System.out.println(p.getTitle()); } //多表查询 查询post,post对应一个admin /* 那就要新建一个postMapper.xml <select id="findById" parameterType="int" resultType="Post" resultMap="postMap"> SELECT admin.id,NAME,PASSWORD,post.id AS pid,title,aid FROM admin INNER JOIN post ON admin.id = post.aid WHERE post.id = #{id} </select> <resultMap type="Post" id="postMap"> <id property="id" column="pid"/> <result property="title" column="title"/> <association property="admin" column="aid" javaType="Admin"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="password" column="password"/> </association> </resultMap> 接口 public interface PostMapper { public Post findById(int id); } 程序中 PostMapper mapper = session.getMapper(PostMapper.class); Post post = mapper.findById(1); System.out.println(post.getTitle()); System.out.println(post.getAdmin().getName()); */ /******************************************************/ //记得要提交和关闭 //session.commit(); session.close(); } }