添加 jar包: 创建连接数据库的properties文件:
创建获取sqlSession的工具类:
package com.hhh.utils;
//创建Mybaits的工具类 用于存放sqlSession
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 java.io.InputStream;
public class MybatisUtils {
private static ThreadLocal threadLocal = new ThreadLocal<>();
private static SqlSessionFactory sqlSessionFactory = null; // 基于单例模式来创建
static {
//创建sqlSessionFactory
InputStream is = null;
try{
is = Resources.getResourceAsStream("mybatis-cfg.xml");
}catch (Exception e){
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}
//获取sqlSession
public static SqlSession getSqlSession(){
SqlSession sqlSession = threadLocal.get();
if(sqlSession == null){
sqlSession = sqlSessionFactory.openSession();
threadLocal.set(sqlSession);
}
return sqlSession;
}
//关闭SqlSession
public static void closeSqlSession(){
SqlSession sqlSession = threadLocal.get();
if(sqlSession != null ){
sqlSession.close();
threadLocal.set(null);
}
}
}
创建全局配置文件:
创建映射配置文件:
创建接口:
测试类:
新 创建一个表roles表在数据库中:
CREATE TABLE `roles` ( `roleid` int(11) NOT NULL AUTO_INCREMENT, `rolename` varchar(20) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, PRIMARY KEY (`roleid`), UNIQUE KEY `roles_fk` (`user_id`) USING BTREE, ConSTRAINT `roles_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`userid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;修改Users实体:就是在Users里面添加Roles中的一个实体: 修改映射配置文件: 测试:
一对多的关系外键必然在多方
创建order表:
创建Orders实体: 修改Users实体: 修改映射配置文件:
修改接口添加抽象方法:
测试:
创建items表:
CREATE TABLE `items` ( `itemid` int(11) NOT NULL AUTO_INCREMENT, `itemname` varchar(20) DEFAULT NULL, `itemprice` double DEFAULT NULL, PRIMARY KEY (`itemid`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;创建order_item中间表: 多对多关系必须要依赖一个中间表 创建Items实体: 在Orders中修改实体类Orders:
修改映射配置文件:
SELECT * from users as u ,orders as o,orders_items as oi ,items as i where u.userid = o.user_id and o.orderid = oi.order_id and oi.item_id = i.itemid and u.userid = #{userid}
修改接口:
测试:
修改映射配置文件:
修改接口:
测试:



