mybatis笔记整理

1、测试mybatis在java文件中取得数据表中的内容

 

2、xml核心配置文件详解

3、数据库连接池

4、编码问题

三种查询方式

log4j

mapper.xml中的parameterType属性

分页

别名

新增和事务讲解

测试网页分页

getMapper接口绑定方案和多参数传递

动态sql

threadlocal

缓存

mybatis注解

运行原理

1、测试mybatis,在java中取到数据库表内容

Mybatis.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="default">

    <environment id="default">

      <transactionManager type="JDBC"/>

      <dataSource type="POOLED">

        <property name="driver" value="com.mysql.jdbc.Driver"/>

        <property name="url" value="jdbc:mysql:///ssm1"/>

        <property name="username" value="root"/>

        <property name="password" value="123"/>

      </dataSource>

    </environment>

  </environments>

  <mappers>

    <mapper resource="com/pshdhx/mapper/FlowerMapper.xml"/>

  </mappers>

</configuration>

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="a.b">

    <select id="selAll" resultType="com.pshdhx.pojo.Flower">

       select * from flower

    </select>

</mapper>

Test.java

package com.pshdhx.test;

 

import java.io.IOException;

import java.io.InputStream;

import java.util.List;

 

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 com.pshdhx.pojo.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();

       List<Flower> list = session.selectList("a.b.selAll");

       for(Flower flower:list){

           System.out.println(flower.toString());

       }

       session.close();

    }

}

 

 

 

 

 

 

 

2、Xml核心配置文件详解

 

3、数据库连接池:

4、编码问题

res.setContentType("text/html;charset=utf-8");

记住:是request,是text形式请求

 

三种查询方式:

Session.selectList()

Session.selectOne()

 

Session.selectMap()

测试people输出到jsp页面

有pojo实体类,xml核心配置文件,xml映射文件,service,servlet

package com.pshdhx.service.impl;

import java.io.IOException;

import java.io.InputStream;

/**

 * 在数据访问层和控制器中处理异常,在service层中只抛出异常

 */

import java.util.List;

 

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 com.pshdhx.pojo.People;

import com.pshdhx.service.PeopleService;

 

public class PeopleServiceImpl implements PeopleService {

 

         @Override

         public List<People> show() throws IOException {

                  InputStream is = Resources.getResourceAsStream("mybatis.xml");

                  /**

                   * 前面是工厂,实例化工厂对象时使用的是  构建者模式:意义:简化对象实例化的过程,就是is流的转化的过程,省去了configuration和parse过程,不用new工厂了

                   *   有适配器设计模式 adapter

                   */

                  SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

                  SqlSession session  = factory.openSession();

                  List<People> list = session.selectList("com.pshdhx.mapper.PeopleMapper.selAll");

                  session.close();

                  return list;

         }

 

}

<?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.pshdhx.mapper.PeopleMapper">

    <select id="selAll" resultType="com.pshdhx.pojo.People">

       select * from people

    </select>

</mapper>

<?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="default">

    <environment id="default">

      <transactionManager type="JDBC"/>

      <dataSource type="POOLED">

        <property name="driver" value="com.mysql.jdbc.Driver"/>

        <property name="url" value="jdbc:mysql:///ssm1"/>

        <property name="username" value="root"/>

        <property name="password" value="123"/>

      </dataSource>

    </environment>

  </environments>

  <mappers>

    <mapper resource="com/pshdhx/mapper/PeopleMapper.xml"/>

  </mappers>

</configuration>

package com.pshdhx.servlet;

 

import java.io.IOException;

import java.util.List;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.pshdhx.pojo.People;

import com.pshdhx.service.PeopleService;

import com.pshdhx.service.impl.PeopleServiceImpl;

 

@WebServlet("/show")

public class ShowServlet extends  HttpServlet{

    private PeopleService peopleService = new PeopleServiceImpl();

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       // TODO Auto-generated method stub

       List<People> list = peopleService.show();

       req.setAttribute("list", list);

       //相对路径

       // /表示项目根目录  即是webcontent目录。

       req.getRequestDispatcher("index.jsp").forward(req, resp);

    }

}

Log4j

log4j.rootCategory=info, CONSOLE ,LOGFILE

 

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

log4j.appender.CONSOLE.layout.ConversionPattern=%C %p  %m %n

 

log4j.appender.LOGFILE=org.apache.log4j.FileAppender

log4j.appender.LOGFILE.File=E:/my.log

log4j.appender.LOGFILE.Append=true

log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout

log4j.appender.LOGFILE.layout.ConversionPattern=%C %m %L %n

 

package com.pshdhx.test;

 

import org.apache.log4j.Logger;

 

public class Test {

    public static void main(String[] args) {

       Logger logger = Logger.getLogger(Test.class);

       logger.debug("这是调试信息");

       logger.info("这是普通信息");

    }

}

 

mybatis中的全部配置文件中使用log4j

<configuration>

    <settings>

       <setting name="logImpl" value="LOG4J"/>

    </settings>

 

Mapper.xml中的parameterType属性

控制参数类型:

找参数:${value} 取值     #{index}这是占位符

如果希望传递多个参数,那么是map

 

 

分页:

int pageSize = 2;

       int pageNumber = 1;

       Map<Object, Object> map = new HashMap<>();

       map.put("pageSize", pageSize);

       map.put("pageStart", pageSize*(pageNumber-1));

       List<People> p = session.selectList("a.b.page",map);//查询id2people

       System.out.println(p);

       session.close();

<select id="page" resultType="com.pshdhx.pojo.People" parameterType="map">

       select * from people limit #{pageStart} , #{pageSize}       <!—两个参数都是map里边的key value值在java类类中被定义了 -->

    </select>

别名:

<typeAliases>

       <package name="com.pshdhx.pojo"/>

    </typeAliases>

 

新增和事务讲解:

    People peo = new People();

       peo.setName("pshdhx");

       peo.setAge(23);

       int index = session.insert("a.b.ins",peo);

        session.commit();

       if(index>0){

           System.out.println("success");

       }else{

           System.out.println("false");

       }

       session.close();

Roolback放在catch里边

测试网页分页:

package com.pshdhx.servlet;

 

import java.io.IOException;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.pshdhx.pojo.PageInfo;

import com.pshdhx.service.PeopleService;

import com.pshdhx.service.impl.PeopleServiceImpl;

@WebServlet("/page")

public class ShowPageServlet extends HttpServlet{

    private PeopleService peopleService = new PeopleServiceImpl();

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       String pageSizeStr = req.getParameter("pageSize");

       int pageSize=2;

       if(pageSizeStr !=null &&!pageSizeStr.equals("")){

           pageSize = Integer.parseInt(pageSizeStr);

       }

       String pageNumberStr =req.getParameter("pageNumber");

       int pageNumber=1;

       if(pageNumberStr!=null&&!pageNumberStr.equals("")){

           pageNumber = Integer.parseInt(pageNumberStr);

       }

      

       PageInfo pi = peopleService.showPage(pageSize, pageNumber);

       req.setAttribute("PageInfo", pi);

       req.getRequestDispatcher("index.jsp").forward(req, resp);

      

    }

}

 

package com.pshdhx.service.impl;

 

import java.io.IOException;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;

 

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 com.pshdhx.pojo.PageInfo;

import com.pshdhx.service.PeopleService;

 

public class PeopleServiceImpl implements PeopleService {

 

    @Override

    public PageInfo showPage(int pageSize, int pageNumber) throws IOException {

       InputStream is = Resources.getResourceAsStream("mybatis.xml");

       SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

       SqlSession session = factory.openSession();

       PageInfo pi = new PageInfo();

       pi.setPageSize(pageSize);

       pi.setPageNumber(pageNumber);

       Map<String,Object> map = new HashMap<>();

       map.put("pageStart", pageSize*(pageNumber-1));

       map.put("pageSize", pageSize);

      

       pi.setList(session.selectList("a.b.selByPage",map));

      

       long count = session.selectOne("a.b.selCount");

       pi.setTotal(count%pageSize==0?count/pageSize:count/pageSize+1);

       return pi;

    }

 

}

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

    <table border="1">

       <tr>

           <th>编号</th>

           <th>姓名</th>

           <th>年龄</th>

       </tr>

       <c:forEach items="${PageInfo.list }" var="pi">

           <tr>

              <td>${ pi.id}</td>

              <td>${ pi.name}</td>

              <td>${ pi.age}</td>

           </tr>

       </c:forEach>

    </table>

    <a href="page?pageNumber=${PageInfo.pageNumber-1 }&pageSize=${PageInfo.pageSize}" <c:if test="${PageInfo.pageNumber<=1 }"> οnclick="javascript:return false;" </c:if>>上一页</a>

    <a href="page?pageNumber=${PageInfo.pageNumber+1 }&pageSize=${PageInfo.pageSize}" <c:if test="${PageInfo.pageNumber>=PageInfo.total }"> οnclick="javascript:return false;" </c:if>>下一页</a>

</body>

</html>

转账功能:

AccountMapper.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="a.b">

    <!-- 根据帐号和密码查询账户信息 -->

    <select id="selByAccnoPwd" resultType="account" parameterType="account">

       select * from account where accno=#{accNo} and password=#{password}

    </select>

    <!-- 根据帐号和姓名查询账户信息 -->

    <select id="selByAccnoName" resultType="account" parameterType="account">

       select * from account where accno=#{accNo} and name=#{name}

    </select>

    <!-- 根据accNo修改账户余额 -->

    <update id="updBalanceByAccno" parameterType="account">

       update account set balance=balance+#{balance} where accno=#{accNo}

    </update>

</mapper>

loggerMapper.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="a.Log">

    <insert id="insLog" parameterType="log">

       insert into log values(default,#{accOut},#{accIn},#{money})

    </insert>

    <select id="selByPage" resultType="log" parameterType="map">

       select * from log limit #{pageStart},#{pageSize}

    </select>

    <select id="selCount" resultType="long">

       select count(*) from log

    </select>

</mapper>

Accountserviceimpl.java

public int transfer(Account accIn, Account accOut) throws IOException {

       InputStream is = Resources.getResourceAsStream("mybatis.xml");

       SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

       SqlSession session = factory.openSession();     

       //先判断帐号和密码是否匹配

       Account accOutSelect = session.selectOne("a.b.selByAccnoPwd",accOut);

       if(accOutSelect!=null){

           if(accOutSelect.getBalance()>=accOut.getBalance()){

              Account accInSelect  = session.selectOne("a.b.selByAccnoName",accIn);

              if(accInSelect!=null){

                  accIn.setBalance(accOut.getBalance());

                  accOut.setBalance(-accOut.getBalance());

                  int index = session.update("a.b.updBalanceByAccno",accOut);

                  index += session.update("a.b.updBalanceByAccno",accIn);

                  if(index==2){

                     //日志表记录

                     Log log  = new Log();

                     log.setAccIn(accIn.getAccNo());

                     log.setAccOut(accOut.getAccNo());

                     log.setMoney(accIn.getBalance());

                     session.insert("a.Log.insLog",log);

                     //日志文件记录

                     Logger logger = Logger.getLogger(AccountServiceImpl.class);

                     logger.info(log.getAccOut()+""+log.getAccIn()+""+new Date().toLocaleString()+"转了"+log.getMoney());

                    

                     session.commit();

                     session.close();

                     return SUCCESS;

                  }else{

                     session.rollback();

                     session.close();

                     return ERROR;

                  }

              }else{

                  return ACCOUNT_NAME_NOT_MATCH;

              }

           }else{

              //余额不足

               return ACCOUNT_BALANCE_NOT_ENOUGH;

           }

       }else{

           //帐号和密码不匹配

           return ACCOUNT_PASSWORD_NOT_MATCH;

       }

    }

Logserviceimpl.java

 

package com.pshdhx.service.impl;

/**

 * 这是后台的分页逻辑

 */

import java.io.IOException;

import java.io.InputStream;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

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 com.pshdhx.pojo.Log;

import com.pshdhx.pojo.PageInfo;

import com.pshdhx.service.LogService;

 

public class LogServiceImpl implements LogService{

 

    @Override

    public PageInfo showPage(int pageSize, int pageNumber) throws IOException {

       InputStream is = Resources.getResourceAsStream("mybatis.xml");

       SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

       SqlSession session = factory.openSession();

       Map<String,Object> map = new HashMap<>();

       map.put("pageStart", pageSize*(pageNumber-1));

       map.put("pageSize", pageSize);

      

      

       List<Log> list = session.selectList("a.Log.selByPage",map);

       long count  = session.selectOne("a.Log.selCount");

       PageInfo pi = new PageInfo();

       pi.setList(list);

       pi.setPageNumber(pageNumber);

       pi.setPageSize(pageSize);

       pi.setTotal(count%pageSize==0?count/pageSize:count/pageSize+1);

       return pi;

    }

   

}

ShowlogServlet.java

package com.pshdhx.servlet;

/**

 * 此界面是对后台数据的显示,是后台对数据的响应操作,把数据表中的数据传递到前台,不需要name值,只要coreforeach即可

 */

import java.io.IOException;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.pshdhx.service.LogService;

import com.pshdhx.service.impl.LogServiceImpl;

@WebServlet("/show")

public class ShowServlet extends HttpServlet{

   

    private LogService logService = new LogServiceImpl();

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       // TODO Auto-generated method stub

       int pageSize = 2;

       String pageSizeStr = req.getParameter("pageSize");

       if(pageSizeStr!=null&&!pageSizeStr.equals("")){

           pageSize =Integer.parseInt(pageSizeStr);

       }

       int pageNumber = 1;

       String pageNumberStr = req.getParameter("pageNumber");

       if(pageNumberStr!=null&&!pageNumberStr.equals("")){

           pageNumber = Integer.parseInt(pageNumberStr);

       }

      

       //以上都是为了pageSizepageNumber做准备,调用了serviceimpl的方法。

       req.setAttribute("pageinfo", logService.showPage(pageSize, pageNumber));

       req.getRequestDispatcher("/log.jsp").forward(req, resp);

    }

}

transferServlet.java

package com.pshdhx.servlet;

/**

 * 此界面是前台写数据,后台改变数据,是前台对后台的修改操作。对应的index.jsp中的form表单中都有name的属性值,方便操作。

 */

import java.io.IOException;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

 

import com.pshdhx.pojo.Account;

import com.pshdhx.service.AccountService;

import com.pshdhx.service.impl.AccountServiceImpl;

@WebServlet("/transfer")

public class TransferServlet extends HttpServlet{

    private AccountService accountService = new AccountServiceImpl();

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       // TODO Auto-generated method stub

       req.setCharacterEncoding("utf-8");

       Account accOut  = new Account();

        accOut.setAccNo(req.getParameter("accOutAccNo"));

        accOut.setPassword(Integer.parseInt(req.getParameter("accOutPassword")));

        accOut.setBalance(Double.parseDouble(req.getParameter("accOutBalance")));

      

      

       Account accIn = new Account();

       accIn.setAccNo(req.getParameter("accInAccNo"));

       accIn.setName(req.getParameter("accInName"));

      

      

       //以上一切都是为了调用serviceimpl中的方法的参数做准备。此为方法的返回值,根据返回值判断执行的状态

       int index = accountService.transfer(accIn, accOut);

      

      

       //转账成功之后,服务器端会给出响应,跳转到 show界面  所以是 response

       if(index==AccountService.SUCCESS){

           System.out.println("转账成功");

           //resp.sendRedirect(req.getContextPath()+"/log.jsp");

           resp.sendRedirect(req.getContextPath()+"/show");

       }else{

           HttpSession session = req.getSession();

           session.setAttribute("code", index);

           resp.sendRedirect("/bank/error/error.jsp");

           System.out.println("转账失败");

       }

    }

}

getMapper接口绑定方案和多参数传递

public interface LogMapper {

    List<Log> selAll() throws IOException;

    List<Log> selByAccInAccOut(String accIn,String accOut) throws IOException;

}

<?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.pshdhx.mapper.LogMapper">

    <select id="selAll" resultType="Log">

       select * from log

    </select>

    <select id="selByAccInAccOut" resultType="Log" >

       select * from log where accin=#{param1} and accout=#{param2}

    </select>

</mapper>

package com.pshdhx.test;

 

import java.io.IOException;

import java.io.InputStream;

import java.util.List;

 

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 com.pshdhx.mapper.LogMapper;

import com.pshdhx.pojo.Log;

 

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();

       //实例化接口,初始化session.getMapper(接口); proxy代理模式

       /**

        * 接口为什么实例化

        * 需要给接口一个实例化对象 proxy  jdk的动态代理模式,面向接口(必须有接口)

        * mybatis的好处:每次都要写session.selectList(里边的参数不用写了,更重要的是避免了多参数的问题转为map);

        */

       LogMapper logMapper = session.getMapper(LogMapper.class);

       List<Log> list = logMapper.selAll();

       for(Log log:list){

           System.out.println(log);

       }

       System.out.println("--------------------------------------------");

       List<Log> list2 = logMapper.selByAccInAccOut("1", "3");

       for(Log log:list2){

           System.out.println(log);

       }

       session.close();

       System.out.println("程序执行结束");

    }

}

动态sql

根据不同的条件需要执行不同的sql命令

在xml中添加逻辑判断

 

Where:去掉最前边的and,加where关键字

 

Set:去掉最后边的逗号,加set关键字

Trim:去掉前边的和后边的东西

Bind:模糊查询,拼接字符串

 

threadLocal

缓存:

缓存的是statement对象,尽管sql语句一样,但是执行两次sql语句。

 

Mybatis注解:

 

运行原理:

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值