有事没事领个红包

mybatis开发流程,增删改查

一、开发流程

1)引jar包

//mybatis_core
mybatis3.4core\asm-5.2.jar
mybatis3.4core\cglib-3.2.5.jar
mybatis3.4core\commons-logging-1.2.jar
mybatis3.4core\log4j-1.2.17.jar
mybatis3.4core\mybatis-3.4.4.jar

//db connector
DB-connector\mysql-connector-java-5.1.40-bin.jar

2)变写实体类Student

package com.huitong.entity;

public class Student {
    
    private Integer id;
    private String sname;
    private double salary;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    
    
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    @Override
    public String toString() {
        return sname + ":" + salary;
    }

}
View Code

3)写映射文件StudentMapper.xml,配置mybatis.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.huitong.entity.Student">

    <!-- 映射实体域表的关系
        type:实体全路径名
        id:映射唯一名
     -->
    <resultMap type="com.huitong.entity.Student" id="studentMap">
        <!-- id:主键属性
            result:非主键属性
            property:实体属性名
            column:表的字段
         -->
        <id column="id" property="id"/>
        
        <result column="sname" property="sname"/>
        <result column="salary" property="salary"/>
        
    
    </resultMap>
    
    <!-- 
        insert:插入语句
        parameterType:方法参数,如果是类:必须使用类全路径
        
     -->
    <insert id="add">
        INSERT INTO student(sname, salary) VALUES("allen",34.23);
    </insert>
    
    <insert id="add2" parameterType="com.huitong.entity.Student" >
        INSERT INTO student(sname, salary) VALUES(#{sname},#{salary});
    </insert>
    
    <select id="getStudentById" parameterType="int" resultType="com.huitong.entity.Student">
        SELECT id,sname,salary FROM student WHERE id=#{id};
    </select>
    
    <select id="getAll" resultType="com.huitong.entity.Student">
        SELECT id,sname,salary FROM student;
    </select>
    
    <update id="update" parameterType="com.huitong.entity.Student">
        UPDATE student SET sname=#{sname},salary=#{salary} WHERE id=#{id}
    </update>
    
    <delete id="delete" parameterType="int">
        DELETE FROM student WHERE id=#{id}
    </delete>

</mapper>

注意:如果查询结果返回的对象和数据表中字段,名称名不一致,需要使用resultMap,否则使用resultType。

 

配置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>
    <environments default="mysql">
        <environment id="mysql">            
            <transactionManager type="jdbc"></transactionManager>
            <dataSource type="pooled">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///day14?useSSL=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    
    </environments>
    
    <mappers>
        <mapper resource="com/huitong/entity/StudentMapper.xml"/>
    </mappers>

</configuration>

 

4)写工具类MybatisUtil

package com.huitong.util.mybatis;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

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 MybatisUtil {
    
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactorysion;
    
    //禁止通过new创建对象
    private MybatisUtil(){}
    
    /**
     * 加载mybatis配置文件
     */
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactorysion = new SqlSessionFactoryBuilder().build(reader);
            
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        
    }
    
    /**
     * 获取sqlsession
     * @return
     */
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            sqlSession = sqlSessionFactorysion.openSession();
            threadLocal.set(sqlSession);
            
        }
        return sqlSession;
    }
    
    /**
     * 关闭sqlsession
     */
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        
        if(sqlSession != null){
            //关闭sqlsession
            sqlSession.close();
            //分离当前线程与sqlsession关系
            threadLocal.remove();
        }
        
    }
    
    public static void main(String[] args) {
         Connection connection = MybatisUtil.getSqlSession().getConnection();
         System.out.println(connection!=null?"连接成功":"没有连接成功");
        
    }
    

}
View Code

5)StudentDao数据持久层Dao

package com.huitong.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.huitong.entity.Student;
import com.huitong.util.mybatis.MybatisUtil;
import com.huitong.util.mybatis.mybatisutil2;

public class StudentDao {
    
    /**
     * 增加学生
     * @throws Exception
     */
    public void add() throws Exception{
        SqlSession sqlSession = null;
        
        try{
            sqlSession = MybatisUtil.getSqlSession();
            int n = sqlSession.insert("com.huitong.entity.StudentMapper.add");
            
            System.out.println(n);
            sqlSession.commit();
            
        } catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            
        } finally {
            MybatisUtil.closeSqlSession();
            
        }
        
    }
    
    public void add2(Student stu) throws Exception{
        SqlSession sqlSession = null;
        
        try{
            sqlSession = MybatisUtil.getSqlSession();
            int n = sqlSession.insert("com.huitong.entity.StudentMapper.add2",stu);
            
            System.out.println(n);
            sqlSession.commit();
            
        } catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            
        } finally {
            MybatisUtil.closeSqlSession();
            
        }
        
    }
    
    public Student getStudentById(int id) throws Exception{
        
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        
        try{
            Student student = sqlSession.selectOne(Student.class.getName() + ".getStudentById", id);

            return student;
        } catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
            
        } finally {
            MybatisUtil.closeSqlSession();
        }
        
        
    }
    
    public List<Student> getAll() throws Exception{
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        
        try{
            return sqlSession.selectList(Student.class.getName() + ".getAll");
            
            
        } catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
            
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    
    public void update(Student stu) throws Exception{
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        
        try{
            int n = sqlSession.update(Student.class.getName() + ".update",stu);
            System.out.println(n);
            
            sqlSession.commit();
            
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }finally{
            MybatisUtil.closeSqlSession();
            
        }
        
    }
    
    public void delete(int id){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        
        try{
            int n = sqlSession.delete(Student.class.getName() + ".delete", id);
            System.out.println(n);
            
            sqlSession.commit();
        } catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            
            throw new RuntimeException(e);
        } finally{
            MybatisUtil.closeSqlSession();
            
        }
    }
    
    public static void main(String[] args) {
        StudentDao studentDao = new StudentDao();
//        Student stu = new Student();
//        stu.setId(2);
//        stu.setSname("beed");
//        stu.setSalary(20.12);
//        
        try {
            studentDao.delete(3);
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
View Code

 

posted @ 2017-05-14 21:16  crazyCodeLove  阅读(985)  评论(0编辑  收藏  举报