目录
一、mybatis环境搭建
1、导入jar包
2、在 src下新建全局配置文件(JDBC四个变量)
3、新建以Mapper结尾的包,在包下新建:实体类名+Mapper.xml
4、测试结果
二、全局配置文件属性详解
1、全局配置文件中内容
三、数据库连接池
1、含义
2、作用
3、实现 JDBC tomcat Pool的步骤
四、三种查询方式
五、log4j
1、使用步骤
2、输出级别
3、设置参数
4、起别名
六、MyBatis接口绑定方案及多参数传递
一、代码实现
1、在mybatis.xml文件,加入包名(FlowerMapper.xml所在的包的位置)
2、写接口
3、在FlowerMapper.xml文件,写入SQL语句(id值与接口名同名)
4、测试
二、起别名(在接口中)
七、动态SQL
1、
2、
3、choose、when、otherwise
4、
5、
6、
7、
8、和
八、ThreadLocal(注意lib放在 WEB-INF目录下)
九、缓存
十、多表查询
1、业务装配
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
3、使用标签
单个对象
多个对象
十一、注解
1、单表的增删改查
2、多表联合
2.1单个对象
2.2多个对象
一、mybatis环境搭建
1、导入jar包
2、在 src下新建全局配置文件(JDBC四个变量)
2.1、没有名称和地址的要求
2.2、在全局配置文件中引入DTD或schema
2.3、全局配置文件内容
3、新建以Mapper结尾的包,在包下新建:实体类名+Mapper.xml
3.1、文件作用:编写需要执行的SQL语句
3.2、把xml文件理解成实现类
3.3、xml文件内容
select * from flower
4、测试结果
public class Test {
public static void main(String[] args) throws IOException {
InputStream is= Resources.getResourceAsStream("mybatis.xml");
//使用工厂设计模式
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
List list = session.selectList("a.b.selAll");
for(Flower flower:list){
System.out.println(flower.toString());
}
session.close();
}
}
查询全部的步骤总结:
1、创建表
2、 导包
3、mybatis.xml文件的配置
4、创建包:com.bjsxt.pojo 包下创建实体类
5、创建包:com.bjsxt.mapper 包下创建 类名+Mapper.xml文件(放置SQL语句)
6、创建包:com.bjsxt.service 包下创建 类名+Service接口
7、创建包:com.bjsxt.serviceImpl 包下创建 实现类继承接口
8、创建包:com.bjsxt.servlet 包下创建ShowServlet类
二、全局配置文件属性详解
1、全局配置文件中内容
1.1
1.1.1、JDBC --》事务管理使用JDBC原生事务管理方式
1.1.2、MANAGED--》 把事务管理转交给其他容器,原生JDBC事务setAutoMapping(false)
1.2、
1.2.1、POOLED--》使用数据库连接池
1.2.2、UNPOOLED--》不使用数据库连接池,和直接使用JDBC一样
1.2.3、JNDI--》java命名目录接口技术
三、数据库连接池
1、含义
在内存中开辟一块空间,存放多个数据库连接对象
2、作用
2.1、在高频率访问数据库时,使用数据库连接池可以降低服务器系统压力,提升程序运行效率
2.2、小型项目不适用于数据库连接池
3、实现 JDBC tomcat Pool的步骤
3.1、在web项目的meta-INF中存放context.xml,在context.xml编写数据库连接池相关属性
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ssm" username="root" password="0000" maxActive="50" maxIdle="20" name="test" auth="Container" maxWait="10000" type="javax.sql.DataSource"
3.2、把项目发布到Tomcat中,数据库连接池就产生了
4、可以在java中使用jndi获取数据库连接池中对象
4.1、Context:上下文接口。context.xml文件对象类型
@WebServlet("/pool")
public class Test02 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Context context= null;
DataSource dataSource=null;
try {
context = new InitialContext();
dataSource= (DataSource) context.lookup("java:/comp/env/test");
Connection conn=dataSource.getConnection();
PreparedStatement ps=conn.prepareStatement("select * from flower");
ResultSet rs=ps.executeQuery();
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
while (rs.next()){
out.print(rs.getInt(1));
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.2、当关闭连接对象时,把连接对象归还给数据库连接池,把状态改变成idle
四、三种查询方式
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is= Resources.getResourceAsStream("mybatis.xml");
//使用工厂设计模式
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
//1、selectList方法
List list = session.selectList("a.b.selAll");
for(Flower flower:list){
System.out.println(flower.toString());
}
//2、selectOne方法
int count =session.selectOne("a.b.selOne");
System.out.println("共"+count+"行");
//3、selectMap方法
//把数据库中的哪个列的值当做map的key
Map
五、log4j
1、使用步骤
1、使用步骤
1.1、导入jar包
1.2、在src下新建log4j.properties(路径和名称都不允许改变)
2、输出级别
2.1、fatal(致命错误)>error(错误)>warn(警告)>info(普通信息)>debug(调试信息)
3、设置参数
4、起别名
4.1、给类起别名。当引用该类时,直接使用 flo 调用
4.2、给某个包下的所有类起别名,别名就是类名。调用该包下的类时,使用原来类名大小写不可以改动
六、MyBatis接口绑定方案及多参数传递
一、代码实现
1、在mybatis.xml文件,加入包名(FlowerMapper.xml所在的包的位置)
2、写接口
public interface FlowerMapper {
List selByIdName(int id ,String name);
}
1、在mybatis.xml文件,加入包名(FlowerMapper.xml所在的包的位置)
2、写接口
public interface FlowerMapper {
List selByIdName(int id ,String name);
}
public interface FlowerMapper {
List selByIdName(int id ,String name);
}
3、在FlowerMapper.xml文件,写入SQL语句(id值与接口名同名)
select * from Flower where id=#{0} and name=#{1}
4、测试
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
FlowerMapper flowerMapper= session.getMapper(FlowerMapper.class);
List list = flowerMapper.selByIdName(1,"矮牵牛");
System.out.println(list);
session.close();
System.out.println("程序执行结束");
}
}
二、起别名(在接口中)
List selByIdName(@Param("i") int id , @Param("n") String name);
七、动态SQL
1、
select * from Flower where 1=1
and id=#{id}
and name=#{name}
2、
2.1、当编写 where标签是,如果内容中第一个是 and 去掉第一个and
2.2、如果中有内容会生成where 关键字,没有内容不生成where 关键字
3、choose、when、otherwise
3.1、若有一个when成立,其他的when不执行
select * from Flower
id=#{id}
and name=#{name}
4、
4.1、当编写 set标签时, 去掉最后一个逗号
4.2、如果中有内容会生成set关键字,没有内容不生成set 关键字
update Flower
id=#{id},
production=#{production},
name=#{name},
where id=#{id}
5、
6、
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
FlowerMapper flowerMapper= session.getMapper(FlowerMapper.class);
List list = flowerMapper.selByIdName(1,"矮牵牛");
System.out.println(list);
session.close();
System.out.println("程序执行结束");
}
}
二、起别名(在接口中)
List selByIdName(@Param("i") int id , @Param("n") String name);
七、动态SQL
1、
select * from Flower where 1=1
and id=#{id}
and name=#{name}
2、
2.1、当编写 where标签是,如果内容中第一个是 and 去掉第一个and
2.2、如果中有内容会生成where 关键字,没有内容不生成where 关键字
3、choose、when、otherwise
3.1、若有一个when成立,其他的when不执行
select * from Flower
id=#{id}
and name=#{name}
4、
4.1、当编写 set标签时, 去掉最后一个逗号
4.2、如果中有内容会生成set关键字,没有内容不生成set 关键字
update Flower
id=#{id},
production=#{production},
name=#{name},
where id=#{id}
5、
6、
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
1、
select * from Flower where 1=1
and id=#{id}
and name=#{name}
2、
2.1、当编写 where标签是,如果内容中第一个是 and 去掉第一个and
2.2、如果中有内容会生成where 关键字,没有内容不生成where 关键字
3、choose、when、otherwise
3.1、若有一个when成立,其他的when不执行
select * from Flower
id=#{id}
and name=#{name}
4、
4.1、当编写 set标签时, 去掉最后一个逗号
4.2、如果中有内容会生成set关键字,没有内容不生成set 关键字
update Flower
id=#{id},
production=#{production},
name=#{name},
where id=#{id}
5、
6、
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
select * from Flower where 1=1 and id=#{id} and name=#{name}
2、
2.1、当编写 where标签是,如果内容中第一个是 and 去掉第一个and
2.2、如果中有内容会生成where 关键字,没有内容不生成where 关键字
3、choose、when、otherwise
3.1、若有一个when成立,其他的when不执行
select * from Flower
id=#{id}
and name=#{name}
4、
4.1、当编写 set标签时, 去掉最后一个逗号
4.2、如果中有内容会生成set关键字,没有内容不生成set 关键字
update Flower
id=#{id},
production=#{production},
name=#{name},
where id=#{id}
5、
6、
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
2.1、当编写 where标签是,如果内容中第一个是 and 去掉第一个and
2.2、如果
3、choose、when、otherwise
3.1、若有一个when成立,其他的when不执行
select * from Flower id=#{id} and name=#{name}
4、
4.1、当编写 set标签时, 去掉最后一个逗号
4.2、如果中有内容会生成set关键字,没有内容不生成set 关键字
update Flower
id=#{id},
production=#{production},
name=#{name},
where id=#{id}
5、
6、
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
4.1、当编写 set标签时, 去掉最后一个逗号
4.2、如果
update Flower id=#{id}, where id=#{id}production=#{production}, name=#{name},
5、
6、
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
6、
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
7、
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
openSession()必须指定(ExecutorType.BATCH)
8、和
8.1、使用标签定义SQL片段
8.2、可以在中使用标签引用
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
8.1、使用
8.2、可以在
八、ThreadLocal(注意lib放在 WEB-INF目录下)
一、含义
线程容器,给线程绑定一个Object内容,只要线程不变,可以随时取出
改变线程后,无法取出该内容
二、与openSession的使用
public class MyBatisUtils {
private static SqlSessionFactory factory;
private static ThreadLocal tl=new ThreadLocal<>();
static{
try{
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session=tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
@WebFilter("/*")
public class OpenSessionInView implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
SqlSession session = MyUtils.getSession();
try{
filterChain.doFilter(servletRequest,servletResponse);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}finally {
MyUtils.closeSession();
}
}
@Override
public void destroy() {
}
}
public interface FlowerMapper {
int ins(Flower flower);
}
insert into flower values(default,#{name},#{price},#{production})
public interface FlowerService {
int ins(Flower flower);
}
public class FlowerServiceImpl implements FlowerService {
@Override
public int ins(Flower flower) {
SqlSession session = MyUtils.getSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
return mapper.ins(flower);
}
}
public class InsertServlet extends HttpServlet{
private FlowerService flowerService=new FlowerServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Flower flower=new Flower();
flower.setName(req.getParameter("name"));
flower.setPrice(Float.parseFloat(req.getParameter("price")));
flower.setProduction(req.getParameter("production"));
int index = flowerService.ins(flower);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}
九、缓存
select * from flower
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session1.close();
SqlSession session2 = factory.openSession();
List list1 = session2.selectList("com.bjsxt.mapper.FlowerMapper.selAll");
session2.close();
}
}
运行结果:
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.0
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Preparing: select * from flower
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG ==> Parameters:
org.apache.ibatis.logging.jdbc.baseJdbcLogger DEBUG <== Total: 7
org.apache.ibatis.cache.decorators.LoggingCache DEBUG Cache Hit Ratio [com.bjsxt.mapper.FlowerMapper]: 0.5
十、多表查询
1、业务装配
在业务(service)把查询的两个结果进行关联
2、使用Auto Mapping 特性,通过别名完成映射(多表单个对象查询)
SELECT t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name
NAME,price,production,tid
FROM flower f LEFT JOIN teacher t ON t.id=f.tid
3、使用标签
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
单个对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
private int tid;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
select * from flower
select * from teacher where id=#{0}
多个对象
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
public class Teacher {
private int id;
private String name;
private List list;
}
select * from flower where tid=#{0}
select * from teacher
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session1 = factory.openSession();
List list = session1.selectList("com.bjsxt.mapper.TeacherMapper.selAll");
System.out.println(list);
session1.close();
}
}
十一、注解
1、单表的增删改查
public interface TeacherMapper {
@Insert("insert into teacher values(#{0},#{1})")
int insertT(int id,String name);
@Delete("delete from teacher where id=#{0}")
int deleteT(int id);
@Update("update teacher set name=#{0} where id=#{1}")
int updateT(String name,int id);
@Select("select * from teacher")
List selAll1();
}
2、多表联合
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
2.1单个对象
public interface FlowerMapper {
@Select("select t.id `teacher.id`,t.name `teacher.name`,f.id id,f.name NAME,price,production,tid from flower f LEFT JOIN teacher t ON t.id=f.tid")
List selAll1();
}
2.2多个对象
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}
public interface FlowerMapper {
@Select("select * from flower where tid=#{0}")
Flower seByTid1(int tid);
}
public interface TeacherMapper {
@Results(value = {
@Result(id=true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.bjsxt.mapper.FlowerMapper.seByTid1"))
})
@Select("select * from teacher")
List selTeacher();
}



