标签:mybatis入门
Mybatis是一个著名的轻量级持久层框架。
在这篇文章中,使用Mybatis框架,实现一个简单的查询事例。后面的文章中会再详细介绍其他用法。
首先,需要导入一些使用的jar,包括:mybatis、commons-logging、mysql-connector-java、log4j等。
在pom.xml中添加dependencies(上边几个项目的依赖):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.vip</groupId> <artifactId>commons-testing</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>commons-testing</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>
新建一张表dq_user:
CREATE TABLE `dq_user` ( `USER_ID` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘用户id‘, `OA_ID` varchar(100) DEFAULT ‘‘ COMMENT ‘用户OA登录ID‘, `NAME` varchar(60) NOT NULL DEFAULT ‘‘ COMMENT ‘用户名称‘, `EMAIL` varchar(60) NOT NULL DEFAULT ‘‘ COMMENT ‘邮件地址‘, `PHONE` varchar(60) NOT NULL DEFAULT ‘‘ COMMENT ‘手机号码‘, `CREATE_TIME` timestamp NOT NULL DEFAULT ‘1980-01-01 00:00:00‘ COMMENT ‘创建时间‘, `UPDATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ‘更新时间‘, `IS_DELETED` tinyint(4) NOT NULL DEFAULT ‘0‘ COMMENT ‘删除标识:0默认,1删除‘, `IS_ADMIN` tinyint(4) NOT NULL DEFAULT ‘0‘ COMMENT ‘管理员标识:0默认,1管理员‘, `IS_ADMIN1` tinyint(4) NOT NULL DEFAULT ‘0‘ COMMENT ‘管理员标识:0默认,1管理员‘, `WEIXIN` varchar(64) NOT NULL DEFAULT ‘‘, PRIMARY KEY (`USER_ID`) ) ENGINE=InnoDB AUTO_INCREMENT=87 DEFAULT CHARSET=utf8 COMMENT=‘用户表‘;
建一个和表对应的java bean类,根据反射机制,调用set方法来给对象赋值,所以,要保证属性名称和表的列字段都相符。同时,生成对应的getter方法、setter方法,并重写toString()。
DqUser.java
package com.vip.model; import java.sql.Timestamp; public class DqUser { //根据反射机制,调用set方法来给对象赋值。 private int user_id; private String oa_id; private String name; private String email; private String phone; private Timestamp create_time; private Timestamp update_time; private int is_deleted; private int is_admin; private int is_admin1; private String weixin; public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getOa_id() { return oa_id; } public void setOa_id(String oa_id) { this.oa_id = oa_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Timestamp getCreate_time() { return create_time; } public void setCreate_time(Timestamp create_time) { this.create_time = create_time; } public Timestamp getUpdate_time() { return update_time; } public void setUpdate_time(Timestamp update_time) { this.update_time = update_time; } public int getIs_deleted() { return is_deleted; } public void setIs_deleted(int is_deleted) { this.is_deleted = is_deleted; } public int getIs_admin() { return is_admin; } public void setIs_admin(int is_admin) { this.is_admin = is_admin; } public int getIs_admin1() { return is_admin1; } public void setIs_admin1(int is_admin1) { this.is_admin1 = is_admin1; } public String getWeixin() { return weixin; } public void setWeixin(String weixin) { this.weixin = weixin; } @Override public String toString() { return "DqUser [user_id=" + user_id + ", oa_id=" + oa_id + ", name=" + name + ", email=" + email + ", phone=" + phone + ", create_time=" + create_time + ", update_time=" + update_time + ", is_deleted=" + is_deleted + ", is_admin=" + is_admin + ", is_admin1=" + is_admin1 + ", weixin=" + weixin + "]"; } }
建立一个配置文件,在这里实现2个功能:配置数据源、注册表的配置文件(xml)。按照规范,命名为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> <environments default="development"> <environment id="development"> <!-- 在实际项目中,数据库环境配置,如果和spring整合,就不需要配置,交给spring处理 --> <transactionManager type="JDBC"/> <!-- 事务管理器 --> <dataSource type="POOLED"> <!-- 连接数据库类型:连接池 、非连接池连接--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://10.199.242.160:3306/vip_ds"/> <property name="username" value="ds"/> <property name="password" value="admin"/> </dataSource> </environment> </environments> <!-- 每张表的映射文件,管理每张表的映射文件。 规范:按照表名的驼峰模式,最后加个Mapper --> <!-- resource 引入映射文件,包分割使用/而不是. --> <mappers> <mapper resource="com/vip/mapping/DqUserMapper.xml"/> </mappers> </configuration>
该配置文件需要放置在classpath下,下图是我的工程的目录结构,当然也可以做相应调整:
下面是Mapper的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.vip.mapping.DsqlUserMapper"> <select id="selectUser" parameterType="java.lang.Integer" resultType="com.vip.model.DqUser"> select * from dq_user where user_id = #{id} </select> </mapper>
测试类AppTest.java:
package com.vip.commons_testing; import static org.junit.Assert.*; 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.Before; import org.junit.Test; import com.vip.model.DqUser; public class AppTest { SqlSessionFactory sqlSessionFactory; @Before public void before() throws IOException { InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } @Test public void test() { SqlSession sqlsession = sqlSessionFactory.openSession(); //第一个参数找到执行的SQL,命名空间.sqlid 第二个参数 DqUser du = sqlsession.selectOne("com.vip.mapping.DsqlUserMapper.selectUser", 80); System.out.println(du); sqlsession.close(); } }
执行结果:
DqUser [user_id=80, oa_id=ere, name=ee, email=334@3434.com, phone=wr, create_time=2016-05-10 10:11:32.0, update_time=2016-06-01 11:21:59.0, is_deleted=1, is_admin=0, is_admin1=0, weixin=]
本文出自 “雪花” 博客,请务必保留此出处http://6216083.blog.51cto.com/6206083/1839335
标签:mybatis入门
原文地址:http://6216083.blog.51cto.com/6206083/1839335