zoukankan      html  css  js  c++  java
  • mybatis开发流程,增删改查

    一、开发流程

    1)引jar包

    //mybatis_core
    mybatis3.4coreasm-5.2.jar
    mybatis3.4corecglib-3.2.5.jar
    mybatis3.4corecommons-logging-1.2.jar
    mybatis3.4corelog4j-1.2.17.jar
    mybatis3.4coremybatis-3.4.4.jar
    
    //db connector
    DB-connectormysql-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
  • 相关阅读:
    日志统计|2018年蓝桥杯B组题解析第八题-fishers
    螺旋折线|2018年蓝桥杯B组题解析第七题-fishers
    递增三元组|2018年蓝桥杯B组题解析第六题-fishers
    乘积尾零|2018年蓝桥杯B组题解析第三题-fishers
    明码|2018年蓝桥杯B组题解析第二题-fishers
    第几天|2018年蓝桥杯B组题解析第一题-fishers
    2016年蓝桥杯B组C/C++省赛(预选赛)题目解析
    2016年蓝桥杯B组C/C++省赛(预选赛)试题
    计蒜客习题:同余方程
    数论——同余方程
  • 原文地址:https://www.cnblogs.com/zhaopengcheng/p/6853846.html
Copyright © 2011-2022 走看看