---Mybatis3学习笔记(2)
生活随笔
收集整理的這篇文章主要介紹了
---Mybatis3学习笔记(2)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 configurationPUBLIC "-//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.?
轉載于:https://www.cnblogs.com/ggzhangblog/p/6399510.html
總結
以上是生活随笔為你收集整理的---Mybatis3学习笔记(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python面向对象-特殊成员
- 下一篇: 初学Netty(杰哥好久不见)