Mybatis案例

MyBatis

MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。 MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的记录.

mybatis提供一种“半自动化”的ORM实现。
   这里的“半自动化”,是相对Hibernate等提供了全面的数据库封装机制的“全自动化”ORM实现而言,“全自动”ORM实现了POJO和数据库表之间的映射,以及 SQL 的自动生成和执行。

    而mybatis的着力点,则在于POJO与SQL之间的映射关系。

需要的jar包:

 

mybatis需要jar包:mybatis-3.3.0.jar

mysql驱动jar包:mysql-connector-java-5.1.15.-bin.jar

日志记录jar包:log4j.jar

 User.java

package com.kangjie.bean;

import java.util.Date;

public class User {

    private String id;
    private String name;
    private String gender;
    private Date birthday;
    private String cellphone;
    private String email;
    private String hobby;
    private String type;
    private String description;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getCellphone() {
        return cellphone;
    }
    public void setCellphone(String cellphone) {
        this.cellphone = cellphone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    } 
}

创建方法接口UserMapper.java和定义操作user表的sql映射文件UserMapper.xml

 

package com.kangjie.mapper;

import java.util.List;

import com.kangjie.bean.User;

public interface UserMapper {

    /**
     * 
     * @param user
     * @return
     * @throws Exception
     */
    public int addUser(User user) throws Exception;
    
    public int updateUser(User user) throws Exception;
    
    public int deleteUser(String id) throws Exception;
    public int findUserByID(String id) throws Exception;
    public List<User> getAllUser() throws Exception;
}

 UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kangjie.mapper.UserMapper">
<!-- 自定义结果返回集 -->
    <resultMap type="User" id="userMap">
        <id property="id" column="id" javaType="java.lang.String"></id>
        <result property="name" column="name" javaType="java.lang.String"></result>
        <result property="gender" column="gender" javaType="java.lang.String"></result>
        <result property="birthday" column="birthday" javaType="java.util.Date"></result>
        <result property="cellphone" column="cellphone" javaType="java.lang.String"></result>
        <result property="email" column="email" javaType="java.lang.String"></result>
        <result property="hobby" column="hobby" javaType="java.lang.String"></result>
        <result property="type" column="type" javaType="java.lang.String"></result>
        <result property="description" column="description" javaType="java.lang.String"></result>
    </resultMap>
<!-- 标签中的id属性必须和接口中的方法名相同,id必须唯一 -->
<!-- keyProperty:仅对insert有效,MyBatis通过getGeneratedKeys或者通过insert语句的selectKey 子元素设置它的值 -->
    <insert id="addUser" useGeneratedKeys="true" keyProperty="id">
        insert into teacher (id,name,gender,birthday,cellphone,email,hobby,type,description) values (#{id},#{name},#{gender},#{birthday},#{cellphone},#{email},#{hobby},#{type},#{description})
    </insert>

</mapper>

为mybatis.cfg.xml里注册UserMapper.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="dbcfg.properties"></properties>
<!-- 为Java Bean起别名-->
<typeAliases>
    <typeAlias type="com.kangjie.bean.User" alias="User"/>
</typeAliases>

<!-- 配置mybatis运行环境 -->
<environments default="cybatis">

<environment id="cybatis">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="JDBC" />
<!-- mybatis提供了3种数据源类型,分别是POOLED,UNPOOL,JNDI -->
<!-- POOLED 表示支持JDBC数据源连接池 -->
<!-- UNPOOLED 表示不支持数据源连接池 -->
<!-- JNDI 表示支持外部数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
<!-- </transactionManager> -->
</environment>
</environments>

<mappers>
<!-- 告知映射文件方式 -->
    <!-- <package name="com/kangjie/mapper/UserMapper.xml"/> -->
    <mapper resource="com/kangjie/mapper/UserMapper.xml"/>
</mappers>
</configuration>

创建工具类

package com.kangjie.tools;

import java.io.IOException;
import java.io.Reader;

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 DBTools {

    public static SqlSessionFactory sessionFactory;
    static{
        try {
            //使用MyBatis提供的Resource类加载mybaits的配置文件
//            Reader reader = Resources.getResourceAsReader("/MyBatis/src/mybatis.cfg.xml");
            Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
            //构建sqlsession工厂
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    //创建能执行映射文件中的sql的sqlSession
    public static SqlSession getSession(){
        return sessionFactory.openSession();
    }
}

测试插入数据

package com.kangjie.service;

import java.util.Date;

import org.apache.ibatis.session.SqlSession;

import com.kangjie.bean.User;
import com.kangjie.mapper.UserMapper;
import com.kangjie.tools.DBTools;

public class UserService {

    public static void main(String[] args) {
        addUser();
    }

    private static void addUser() {
        // TODO Auto-generated method stub
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = new User();
        user.setId("6");
        user.setName("wang");
        user.setGender("2");
        user.setBirthday(new Date());
        user.setCellphone("13343462545");
        user.setDescription("do what I want , when I want");
        user.setEmail("67556677@qq.com");
        user.setHobby("a have fun");
        user.setType("vip");
        
        try {
            mapper.addUser(user);
            session.commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            session.rollback();
        }
    }
}

 

posted @ 2016-12-29 14:09  kangjie  阅读(192)  评论(0编辑  收藏  举报