MyBatis入门
mybaitis_demo004
│ mybaitis_demo004.iml
│ pom.xml
│
└─src
├─main
│ ├─java
│ │ └─com
│ │ └─lifeibai
│ │ ├─mapper
│ │ │ OrdersMapper.java
│ │ │ UserMapper.java
│ │ │
│ │ └─po
│ │ Orders.java
│ │ User.java
│ │
│ └─resources
│ │ db.properties
│ │ log4j.properties
│ │ mybatis-conf.xml
│ │ mybatis.sql
│ │
│ └─com
│ └─lifeibai
│ └─mapper
│ OrdersMapper.xml
│ UserMapper.xml
│
└─test
└─java
└─com
└─lifeibai
└─test
MyTest.java
sql数据库数据 mybatis.sql
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50521
Source Host : localhost:3306
Source Database : mybatis
Target Server Type : MYSQL
Target Server Version : 50521
File Encoding : 65001
Date: 2015-04-09 16:03:53
*/
create database mybatis_db;
use mybatis_db;
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `orders`
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '下单用户id',
`number` varchar(32) NOT NULL COMMENT '订单号',
`createtime` datetime NOT NULL COMMENT '创建订单时间',
`note` varchar(100) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
KEY `FK_orders_1` (`user_id`),
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of orders
-- ----------------------------
INSERT INTO `orders` VALUES ('3', '1', '1000010', '2015-02-04 13:22:35', null);
INSERT INTO `orders` VALUES ('4', '1', '1000011', '2015-02-03 13:22:41', null);
INSERT INTO `orders` VALUES ('5', '10', '1000012', '2015-02-12 16:13:23', null);
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
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;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五', null, '2', null);
INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');
INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('24', '张三丰', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('25', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('26', '王五', null, null, null);
pom.xml
?xml version="1.0" encoding="UTF-8"?
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"
modelVersion4.0.0/modelVersion
groupIdcom.lifeibai.mybatis/groupId
artifactIdmybaitis_demo003/artifactId
version1.0-SNAPSHOT/version
build
plugins
plugin
groupIdorg.apache.maven.plugins/groupId
artifactIdmaven-compiler-plugin/artifactId
version3.5.1/version
configuration
source1.8/source
target1.8/target
/configuration
/plugin
/plugins
/build
dependencies
!--数据库库驱动--
dependency
groupIdmysql/groupId
artifactIdmysql-connector-java/artifactId
version5.1.6/version
/dependency
!--junit测试--
dependency
groupIdjunit/groupId
artifactIdjunit/artifactId
versionRELEASE/version
/dependency
!--Mybatis--
dependency
groupIdorg.mybatis/groupId
artifactIdmybatis/artifactId
version3.4.5/version
/dependency
!--日志--
dependency
groupIdlog4j/groupId
artifactIdlog4j/artifactId
version1.2.17/version
/dependency
/dependencies
/project
com.lifeibai.po.User.java
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
.....
}
db.properties
!--jdbc连接数据库配置信息--
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_db?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
mybatis-conf.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
!-- 配置属性 再加载外部属性,如果有同名属性会覆盖 --
properties resource="db.properties"/
!-- 和spring整合后 environments配置将废除--
environments default="development"
environment id="development"
!-- 使用jdbc事务管理--
transactionManager type="JDBC" /
!-- 数据库连接池--
dataSource type="POOLED"
property name="driver" value="${jdbc.driver}" /
property name="url" value="${jdbc.url}" /
property name="username" value="${jdbc.username}" /
property name="password" value="${jdbc.password}" /
/dataSource
/environment
/environments
!-- 加载mapper文件 --
mappers
!-- resource基于classpath查找 --
package name="com.lifeibai"/
/mappers
/configuration
UserMapper.java
package com.lifeibai.mapper;
import com.lifeibai.po.User;
public interface UserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
int insert(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
int insertSelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
User selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
int updateByPrimaryKey(User record);
}
UserMapper.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.lifeibai.mapper.UserMapper"
resultMap id="BaseResultMap" type="com.lifeibai.po.User"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
id column="id" jdbcType="INTEGER" property="id" /
result column="username" jdbcType="VARCHAR" property="username" /
result column="birthday" jdbcType="DATE" property="birthday" /
result column="sex" jdbcType="CHAR" property="sex" /
result column="address" jdbcType="VARCHAR" property="address" /
/resultMap
sql id="Base_Column_List"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
id, username, birthday, sex, address
/sql
select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
select
include refid="Base_Column_List" /
from user
where id = #{id,jdbcType=INTEGER}
/select
delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
delete from user
where id = #{id,jdbcType=INTEGER}
/delete
insert id="insert" parameterType="com.lifeibai.po.User"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
insert into user (id, username, birthday,
sex, address)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE},
#{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR})
/insert
insert id="insertSelective" parameterType="com.lifeibai.po.User"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
insert into user
trim prefix="(" suffix=")" suffixOverrides=","
if test="id != null"
id,
/if
if test="username != null"
username,
/if
if test="birthday != null"
birthday,
/if
if test="sex != null"
sex,
/if
if test="address != null"
address,
/if
/trim
trim prefix="values (" suffix=")" suffixOverrides=","
if test="id != null"
#{id,jdbcType=INTEGER},
/if
if test="username != null"
#{username,jdbcType=VARCHAR},
/if
if test="birthday != null"
#{birthday,jdbcType=DATE},
/if
if test="sex != null"
#{sex,jdbcType=CHAR},
/if
if test="address != null"
#{address,jdbcType=VARCHAR},
/if
/trim
/insert
update id="updateByPrimaryKeySelective" parameterType="com.lifeibai.po.User"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
update user
set
if test="username != null"
username = #{username,jdbcType=VARCHAR},
/if
if test="birthday != null"
birthday = #{birthday,jdbcType=DATE},
/if
if test="sex != null"
sex = #{sex,jdbcType=CHAR},
/if
if test="address != null"
address = #{address,jdbcType=VARCHAR},
/if
/set
where id = #{id,jdbcType=INTEGER}
/update
update id="updateByPrimaryKey" parameterType="com.lifeibai.po.User"
!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
--
update user
set username = #{username,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=DATE},
sex = #{sex,jdbcType=CHAR},
address = #{address,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
/update
/mapper
测试代码MyTest.java
package com.lifeibai.test;
import com.lifeibai.mapper.UserMapper;
import com.lifeibai.po.User;
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 java.io.IOException;
import java.io.InputStream;
public class MyTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void conf() throws IOException{
String resource = "mybatis-conf.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
/**
* TODO MAPPER
*/
@Test
public void test01(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper userDao = session.getMapper(UserMapper.class);
User user = userDao.selectByPrimaryKey(10);
System.out.println(user);
}
}
文章如有错误,请您一定指出,感谢之至!
如果你有不同的见解,欢迎留言,或者加我QQ986320270
图片可能来源于网络,如有侵权请告知。
最后:关注一下呗