mybatis学习之入门实例
博客专区 > caiyezi 的博客 > 博客详情
mybatis学习之入门实例
caiyezi 发表于1年前
mybatis学习之入门实例
  • 发表于 1年前
  • 阅读 1
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

测试版本

mybatis:3.2.8

数据库:mysql

项目结构

jar包准备

mybatis-3.2.8.jar

mysql-connector-java-5.1.39-bin.jar

junit-4.4.jar

log4j-1.2.17.jar

配置文件

1、jdbc.properties配置文件:

jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://127.1.0.1:3306/db_mybatis
jdbc.username=root jdbc.password=root

2、mybatis主要配置文件,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>
    
    <properties resource="jdbc.properties"></properties>
    <typeAliases>
        <typeAlias type="com.cz.model.Student" alias="Student"/>        <!-- 类型别名 -->
    </typeAliases>
    
    <environments default="development">        <!-- 默认开发环境 -->
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="com/cz/mappers/StudentMapper.xml"/>
    </mappers>
    
</configuration>

其中typeAliases是为了指定类型别名,这样使用到com.cz.model.Student类时直接使用Student代替即可。

创建SqlSessionFactoryUtil工具类

该工具类主要是加载mybatis配置文件并通过相应的builder生成session工厂,再从工厂产生sql session对象,这里使用到了单例设计模式(懒汉式):

package com.cz.utill; import java.io.IOException; import java.io.InputStream; 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 SqlSessionFactoryUtil { private static SqlSessionFactory sqlSessionFactory; private SqlSessionFactoryUtil() {} private static SqlSessionFactory getSqlSessionFactory() { if (sqlSessionFactory == null) { // 读取mybatis配置
            InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } return sqlSessionFactory; } public static SqlSession openSession(){ return getSqlSessionFactory().openSession(); } }

创建实体映射类

实体类Student.java,这里只有三个属性:

package com.cz.model; public class Student { private Integer id; private String name; private int age; public Student(String name, int age) { super(); this.name = name; this.age = age; } public Student() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

编写Dao接口

mybatis支持传统的类似hibernate的Dao层封装数据库操作,也支持面向mapper.xml映射文件的动态sql类型,如果使用传统的Dao数据库编程模型的话,需要在相应的Dao类中注入sql session工厂对象(一般通过构造注入),这里使用后一种方式即mapper配置:

package com.cz.mappers; import java.util.List; import com.cz.model.Student; public interface StudentDao { /** * 新增 * @param student * @return
     */
    public int add(Student student); /** * 修改 * @param student * @return
     */
    public int update(Student student); /** * 删除 * @param student * @return
     */
    public int delete(Integer id); /** * 根据id查找 * @param id * @return
     */
    public Student findById(Integer id); /** * 查找 * @param id * @return
     */
    public List<Student> find(); }

mapper.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.cz.mappers.StudentDao">
    
    <resultMap type="Student" id="StudentResult">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>
    
    <!-- 插入 -->
    <insert id="add" parameterType="Student"> insert into t_student values(null,#{name},#{age}) </insert>
    
    <update id="update" parameterType="Student"> update t_student set name = #{name},age = #{age} where id = #{id} </update>
    
    <delete id="delete" parameterType="Integer"> delete from t_student where id = #{id} </delete>
    
    <select id="findById" resultMap="StudentResult" parameterType="Integer"> select * from t_student where id = #{id} </select>
    
    <select id="find" resultMap="StudentResult"> select * from t_student </select>
</mapper>

dao接口跟mapper文件的对应关系如下:

添加log4j日志记录

添加jar包:log4j-1.2.17.jar

编写测试类StudentServiceTest.java:

package com.cz.service; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import com.cz.mappers.StudentDao; import com.cz.model.Student; import com.cz.utill.SqlSessionFactoryUtil; public class StudentServiceTest { public static Logger logger = Logger.getLogger(StudentServiceTest.class); public static void main(String[] args) { SqlSession sqlSession = SqlSessionFactoryUtil.openSession(); StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        //返回student dao接口
        int result = studentDao.add(new Student("张三", 20)); sqlSession.commit(); if (result > 0) { logger.info("测试成功"); } } }

使用junit单元测试

添加junit-4.4.jar,单元测试代码:

package com.cz.test; import java.util.Iterator; 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.cz.mappers.StudentDao; import com.cz.model.Student; import com.cz.utill.SqlSessionFactoryUtil; public class StudentTest { public static Logger logger = Logger.getLogger(StudentTest.class); SqlSession sqlSession = null; StudentDao studentDao = null; // 返回student dao接口
 @Before public void setUp() throws Exception { sqlSession = SqlSessionFactoryUtil.openSession(); studentDao = sqlSession.getMapper(StudentDao.class); logger.info("开始执行了"); } @After public void tearDown() throws Exception { sqlSession.close(); logger.info("执行结束了"); } @Test public void testAdd() throws Exception { Student student = new Student("admin", 22); int result = studentDao.add(student); sqlSession.commit(); if (result > 0) { logger.info("添加成功了"); } } @Test public void testUpdate() throws Exception { Student student = new Student(24, "xxxxxxx", 21); int result = studentDao.update(student); sqlSession.commit(); if (result > 0) { logger.info("修改成功了"); } } @Test public void testDelete() throws Exception { int result = studentDao.delete(26); sqlSession.commit(); if (result > 0) { logger.info("删除成功了"); } } @Test public void testFindById() throws Exception { Student student = studentDao.findById(25); System.out.println(student.toString()); sqlSession.commit(); } @Test public void testFind() throws Exception { List<Student> students = studentDao.find(); // Iterator<Student> iterator = students.iterator(); // while (iterator.hasNext()) { // System.out.println(iterator.next()); // } // for(Student s:students){ // System.out.println(s.toString()); // }
        Student student = null; for (int i = 0; i < students.size(); i++) { student = students.get(i); System.out.println(student.toString()); } sqlSession.commit(); } }

测试结果:

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 1
博文 108
码字总数 0
×
caiyezi
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: