码迷,mamicode.com
首页 > 其他好文 > 详细

---Mybatis3学习笔记(2)

时间:2017-02-15 00:47:38      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:deb   local   cat   url   type属性   string   tag   cep   foreign   

1.先来一个最简单的mybatis操作MySql数据库的例子

  

//(1)定义一个实体类(com.ggzhang.mybatis.pojo.Student)
package com.ggzhang.mybatis.pojo; public class Student { private Integer id; private String name; private int age; private double score; 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; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + "]"; } public Student() { super(); // TODO Auto-generated constructor stub } public Student(Integer id, String name, int age, double score) { super(); this.id = id; this.name = name; this.age = age; this.score = score; } }

生成一个简单的表Student

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(5) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `score` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 1 package com.ggzhang.mybatis.dao;
 2 
 3 import com.ggzhang.mybatis.pojo.Student;
 4 
 5 /**
 6  * 定义dao接口
 7  * 
 8  * @author zhang
 9  * 
10  */
11 public interface StudentDao {
12     void insertStudent(Student student);
13 }

定义映射文件:注意:#{}中写入的是Student类的属性名.对于paramterType属性,框架会自定根据用户执行的SqlSession方法中的参数自动检测到,所以也可以不用指定parameterType属性

<?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.ggzhang.myabtis.dao.StudentDao">
    <insert id="insertStudent" parameterType="com.ggzhang.mybatis.pojo.Student">
        insert into student(id,name,age,score) values(#{id},#{name},#{age},#{score})
    </insert>
</mapper>

定义主配置文件.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>
<!-- 主配置文件: 1)数据库连接信息, 事务配置; 2)加载映射文件 -->

    <!-- 默认使用的环境信息 -->
    <environments  default="developer">
        <!-- 开发环境 -->
        <environment id="developer">
            <!-- 事务管理: 
               type:事务类型   JDBC:使用的Connection的事务管理 commit, rollback 
                            MANAGED: 由容器管理事务(Spring是容器)
               -->
            <transactionManager type="JDBC" />
            
            <!-- 数据源 type:数据源类型
                POOLED : 使用数据库连接池
                UNPOOLED: 不使用数据库的连接池. 每次操作的创建连接, 使用完毕后关闭连接.
                JNDI:  外部数据源
             -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatistest"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
        <!-- 线上环境 -->
        <environment id="online">
            <!-- 事务管理: 
               type:事务类型   JDBC:使用的Connection的事务管理 commit, rollback 
                            MANAGED: 由容器管理事务(Spring是容器)
               -->
            <transactionManager type="JDBC" />
            
            <!-- 数据源配置
                type:数据源类型
                POOLED : 使用数据库连接池
                UNPOOLED: 不使用数据库的连接池. 每次操作的创建连接, 使用完毕后关闭连接.
                JDNI:  外部数据源
             -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatistest"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    <!-- 加载sql映射文件 -->
    <mappers>
        <mapper  resource="com/ggzhang/mybatis/dao/StudentDao.xml"/> 
        <!--  <mapper  url="file:///d:/studentMapper.xml" /> -->
    </mappers>

</configuration>

定义Dao实现类

package com.ggzhang.mybatis.dao;

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;

import com.ggzhang.mybatis.pojo.Student;

public class StudentDaoImpl implements StudentDao {

    private SqlSession session;

    @Override
    public void insertStudent(Student student) {
        try {
            // 读取配置文件
            InputStream inputStream = Resources
                    .getResourceAsStream("mybatis-config.xml");
            // 创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
            // 创建SqlSession对象
            session = sqlSessionFactory.openSession();
            session.insert("insertStudent", student);
            // 提交
            session.commit();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } finally {
            if (session != null) {
                session.close();
            }
        }

    }

}

定义测试类

package com.ggzhang.mybatis.test;

import org.junit.Test;

import com.ggzhang.mybatis.dao.StudentDao;
import com.ggzhang.mybatis.dao.StudentDaoImpl;
import com.ggzhang.mybatis.pojo.Student;

public class MybatisTest {

    @Test
    public void testInsert(){
        StudentDao studentDao = new StudentDaoImpl();
        Student student = new Student(3,"赵六",26,96.5);
        studentDao.insertStudent(student);
        
    }
}

就可以成功的插入数据了,底下是log4j打印出来的信息.包括生成的Sql,

DEBUG [main] - Logging initialized using ‘class org.apache.ibatis.logging.slf4j.Slf4jImpl‘ adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1189752912.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46ea3050]
DEBUG [main] - ==>  Preparing: insert into student(id,name,age,score) values(?,?,?,?) 
DEBUG [main] - ==> Parameters: 3(Integer), 赵六(String), 26(Integer), 96.5(Double)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@46ea3050]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46ea3050]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@46ea3050]
DEBUG [main] - Returned connection 1189752912 to pool.

 

---Mybatis3学习笔记(2)

标签:deb   local   cat   url   type属性   string   tag   cep   foreign   

原文地址:http://www.cnblogs.com/ggzhangblog/p/6399510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!