---Mybatis3学习笔记
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了---Mybatis3学习笔记相关的知识,希望对你有一定的参考价值。
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 [[email protected]]
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 [[email protected]]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [[email protected]]
DEBUG [main] - Closing JDBC Connection [[email protected]]
DEBUG [main] - Returned connection 1189752912 to pool.
以上是关于---Mybatis3学习笔记的主要内容,如果未能解决你的问题,请参考以下文章
[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段