ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 创建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 */ 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); ~~~ # 创建类 创建pojo包 在pojo包下创建User类 ~~~ package pojo; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private static final long serialVersionUID = 1L; 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 + "]"; } } ~~~ 创建sqlmap包 在sqlmap包下创建User.xml也就是sql映射文件 ~~~ <?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,还有一个很重要的作用,后面会讲 --> <mapper namespace="test"> <!-- 通过id查询一个用户 占位符的类型是int 结果映射是自动映射,映射到User中 --> <select id="findUserById" parameterType="Integer" resultType="pojo.User"> select * from user where id = #{v} </select> </mapper> ~~~ # 创建SqlSessionFactory,并根据用户id查询 ~~~ package junit; 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 pojo.User; public class MybatisFirstTest { @Test public void testMybatis() throws Exception { // 加载核心配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 执行sql语句 User user = sqlSession.selectOne("test.findUserById", 1); System.out.println(user); } } ~~~ # 用户名模糊查询 **User.xml** ~~~ <!-- 根据用户名称模糊查询用户列表 #{} select * from user where id=? 占位符 ? == '五' ${} select * from user where username like '%五%' 字符串拼接 --> <select id="findUserByUsername" parameterType="String" resultType="pojo.User"> select * from user where username like #{username} </select> ~~~ **SqlSessionFactory** ~~~ @Test public void testMybatis() throws Exception { // 加载核心配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 执行sql语句 List<User> users = sqlSession.selectList("test.findUserByUsername", "%五%"); for (User user2 : users) { System.out.println(user2); } } ~~~ # 添加用户 **User.xml** ~~~ <!-- 添加用户 --> <insert id="insertUser" parameterType="pojo.User"> insert into user (username,birthday,address,sex) values (#{username},#{birthday},#{address},#{sex}) </insert> ~~~ **SqlSessionFactory** ~~~ @Test public void testMybatis() throws Exception { // 加载核心配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 执行sql语句 User user = new User(); user.setUsername("jdxia"); user.setBirthday(new Date()); user.setAddress("abcdef"); user.setSex("男"); int i = sqlSession.insert("test.insertUser", user); sqlSession.commit(); } ~~~ # 添加用户,并返回用户的id **User.xml** ~~~ <!-- 添加用户 --> <insert id="insertUser" parameterType="pojo.User"> <!-- 把取的值放到对象的id字段上,类型是int, order是mysql自增主键,如果mysql主键是varchar,是你提供那么这写BEFORE,oracle这也写BEFORE --> <selectKey keyProperty="id" resultType="Integer" order="AFTER"> select LAST_INSERT_ID() </selectKey> insert into user (username,birthday,address,sex) values (#{username},#{birthday},#{address},#{sex}) </insert> ~~~ **SqlSessionFactory** ~~~ @Test public void testMybatis() throws Exception { // 加载核心配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 执行sql语句 User user = new User(); user.setUsername("jdxia01"); user.setBirthday(new Date()); user.setAddress("abcdef"); user.setSex("男"); int i = sqlSession.insert("test.insertUser", user); sqlSession.commit(); System.out.println(user.getId()); } ~~~ # 更新用户 **User.xml** ~~~ <!-- 更新 --> <update id="updateUserById" parameterType="pojo.User"> update user set username = #{username},sex= #{sex},birthday= #{birthday},address= #{address} where id = #{id} </update> ~~~ **SqlSessionFactory** ~~~ @Test public void testMybatis() throws Exception { // 加载核心配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 执行sql语句 User user = new User(); user.setId(28); user.setUsername("jdxia11"); user.setBirthday(new Date()); user.setAddress("abcdef"); user.setSex("男"); int i = sqlSession.insert("test.updateUserById", user); sqlSession.commit(); } ~~~ # 删除用户 **User.xml** ~~~ <!-- 删除 --> <delete id="deleteUserById" parameterType="Integer"> delete from user where id =#{v} </delete> ~~~ **SqlSessionFactory** ~~~ @Test public void testMybatis() throws Exception { // 加载核心配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 执行sql语句 int i = sqlSession.insert("test.deleteUserById", 28); sqlSession.commit(); System.out.println(i); } ~~~