mybatis入门
需求:根据id查询用户的信息
mysql数据库:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'王五',NULL,'2',NULL),(10,'张三','2014-07-10','1','北京市'),(16,'张小明',NULL,'1','河南郑州'),(22,'陈小明',NULL,'1','河南郑州'),(24,'张三丰',NULL,'1','河南郑州'),(25,'陈小明',NULL,'1','河南郑州'),(26,'王五',NULL,NULL,NULL);
eclipse中的项目结构:
要引入的jar包:
日志文件:
log4j.properties
# Global logging configuration
#在开发环境下日志级别要设置成DEBUG,生成环境设置成info或error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
pojo类:
package ql.mybatis.pojo; import java.util.Date; public class User { //属性名和数据库的字段对应 private Integer id; private String username;//用户名 private String sex;//性别 private Date birthday;//生日 private String address;//地址 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } }
映射文件:
User.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"> <!-- namespace命名空间,作用就死对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用(刚开始学还不能理解) --> <mapper namespace="test"> <!-- 在映射文件中配置很多sql语句--> <!-- 需求:通过id查询用户表的记录 --> <!-- 通过select 执行数据库的查询 id:标识映射文件的sql 将sql语句封装到mappedStatement对象中,所以将id称为statement的id parameterType:指定输入参数的类型,这里指定int型 #{}表示一个占位符 #{id}:其中的id表示接受输入的参数,参数名称就是id,如果输入的参数是简单类型,#{}中的参数可以任意 resultType:指定sql输出的结果的所映射的java对象类型,select指定restultType表示将单条记录映射成java对象 --> <select id="findUserById" parameterType="int" resultType="ql.mybatis.pojo.User"> select * from User where id=#{id} </select> </mapper>
配置文件:
SqlMapConfig.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> <!-- 和spring整合后 environments配置将废除--> <environments default="development"> <environment id="development"> <!-- 使用jdbc事务管理,由mybatis管理--> <transactionManager type="JDBC" /> <!-- 数据库连接池,由mybatis管理--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="sqlmap/User.xml"/> </mappers> </configuration>
测试类:
package ql.mybatis.first; 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 org.junit.Test; import ql.mybatis.pojo.User; public class MybatisTest { // 根据id查询用户的信息,得到一条记录结果 @Test public void findUserByIdTest() { // 通过工厂得到SqlSession SqlSession sqlSession = null; try { // mybatis配置文件 String resource = "SqlMapConfig.xml"; // 得到配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 创建会话工厂,传入mybatis的配置文件信息 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); // 通过SqlSession操作数据库 // 第一个参数:映射文件中statement的id,等于=namespace+"."+statement的id // 第二个参数:指定和映射文件中所匹配的parameterType类型的参数 // sqlSession.selectOne结果 是与映射文件中所匹配的resultType类型的对象 // selectOne查询出一条记录 User user=sqlSession.selectOne("test.findUserById", 1); System.out.println(user); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(sqlSession!=null){ //释放资源 sqlSession.close(); } } } }
结果:
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 411390898.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@188553b2]
DEBUG [main] - ==> Preparing: select * from User where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
User [id=1, username=王五, sex=2, birthday=null, address=null]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@188553b2]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@188553b2]
DEBUG [main] - Returned connection 411390898 to pool.