mybatis自学历程

Posted 青春-无悔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis自学历程相关的知识,希望对你有一定的参考价值。

传递多个参数

1.在mybatis.xml下<mappers>下使用<package>

<mappers>
        <package name="com.mybatis.mapper"/>
</mappers>

2.在com.mybatis.mapper下新建接口

public interface LogMapper {
    List<Log> sellAll();
    
    List<Log> selByAccInAccOut(Integer accin,Integer accout);
}

3.在com.mybatis.mapper新建一个LogMapper.xml

3.1 namespace 必须和接口全路径(包名+类名)一致

3.2 id值必须和接口中的方法相同

3.3 如果接口中方法为多个参数,可以省略parameterType

3.4.1 #{ } 中使用param+数字,表示第几个参数

<?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.mybatis.mapper.LogMapper">
    <select id="sellAll" resultType="Log">
        select * from log
    </select>
    
    <!-- 当多参数时,不需要写 parameterType-->
    <select id="selByAccInAccOut" resultType="Log" >
        select * from log where accin=#{param1} and accout=#{param2}
    </select>
</mapper>

3.4.2 也可以使用注解

List<Log> selByAccInAccOut(@Param("accin") Integer accin,@Param("accout") Integer accout);
<select id="selByAccInAccOut" resultType="Log" >
        select * from log where accin=#{accin} and accout=#{accout}
</select>

案例

新建项目mybatis05

 

<?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>
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <typeAliases>
        <!-- <typeAlias type="com.mybatis.po.People" alias="peo"/> -->
        <package name="com.mybatis.po" />
    </typeAliases>
    <!-- 配置mybatis运行环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- mysql数据库驱动 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <!-- 连接数据库的URL -->
                <property name="url"
                    value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中 -->
    <mappers>
        <package name="com.mybatis.mapper"/>
    </mappers>
</configuration>
mybatis.xml

 

# Global logging configuration
log4j.rootLogger=Info,stdout,R
# MyBatis logging configuration...
log4j.logger.com.mybatis=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=D\\:\\\\logs\\\\log.log   
log4j.appender.R.layout=org.apache.log4j.PatternLayout
1log4j.appender.R.layout.ConversionPattern=%m %n
log4j.properties

com.mybatis.po包

package com.mybatis.po;

public class Log {
    private int id;
    private String accIn;
    private String accOut;
    private double money;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAccIn() {
        return accIn;
    }
    public void setAccIn(String accIn) {
        this.accIn = accIn;
    }
    public String getAccOut() {
        return accOut;
    }
    public void setAccOut(String accOut) {
        this.accOut = accOut;
    }
    public double getMoney() {
        return money;
    }
    public void setMoney(double money) {
        this.money = money;
    }
    @Override
    public String toString() {
        return "Log [id=" + id + ", accIn=" + accIn + ", accOut=" + accOut + ", money=" + money + "]";
    }
    
}
Log.java

com.mybatis.mapper包

package com.mybatis.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.mybatis.po.Log;

public interface LogMapper {
    List<Log> sellAll();
    
    List<Log> selByAccInAccOut(@Param("accin") Integer accin,@Param("accout") Integer accout);
}
LogMapper.java
<?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.mybatis.mapper.LogMapper">
    <select id="sellAll" resultType="Log">
        select * from log
    </select>
    
    <!-- 当多参数时,不需要写 parameterType-->
    <select id="selByAccInAccOut" resultType="Log" >
        select * from log where accin=#{accin} and accout=#{accout}
    </select>
</mapper>
LogMapper.xml

com.mybatis.test包

package com.mybatis.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.mybatis.mapper.LogMapper;
import com.mybatis.po.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();
        
        LogMapper logMapper=session.getMapper(LogMapper.class);
//        List<Log> list=logMapper.sellAll();
//        for(Log log :list){
//            System.out.println(log);
//        }
        
        List<Log> list=logMapper.selByAccInAccOut(1, 3);
        for(Log log:list){
            System.out.println(log);
        }
        
        session.close();
        
    }
}
Test.java

数据库数据如下

 

 运行结果如下

 

数据查询和分页

 

 数据库

teachar表(由于输入太快,把teacher输成teachar)

 

 student表

 

 sql语句

create table teachar(
id     int(10) primary key auto_increment,
name varchar(20)
);

create table student(
id int(10) primary key auto_increment,
name varchar(20),
age int(3),
tid int(10),
CONSTRAINT fk_teachar FOREIGN key (tid) REFERENCES teachar(id)
);

insert into teachar VALUES(DEFAULT,\'老师1\');
insert into teachar VALUES(DEFAULT,\'老师2\');

insert into student values(DEFAULT,\'学生1\',12,1);
insert into student values(DEFAULT,\'学生2\',12,1);
insert into student values(DEFAULT,\'学生3\',12,1);
insert into student values(DEFAULT,\'学生4\',12,1);
insert into student values(DEFAULT,\'学生5\',12,1);
insert into student values(DEFAULT,\'学生6\',12,1);
insert into student values(DEFAULT,\'学生7\',12,1);
insert into student values(DEFAULT,\'学生8\',12,2);
insert into student values(DEFAULT,\'学生9\',12,2);
insert into student values(DEFAULT,\'学生10\',12,2);

新建项目mybatis07

导入所需jar包和jQuery.js

log4j.properties

# Global logging configuration
log4j.rootLogger=Info,stdout,R
# MyBatis logging configuration...
log4j.logger.com.mybatis=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=D\\:\\\\logs\\\\log.log   
log4j.appender.R.layout=org.apache.log4j.PatternLayout
1log4j.appender.R.layout.ConversionPattern=%m %n
log4j.properties

 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>
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <typeAliases>
        <!-- <typeAlias type="com.mybatis.po.People" alias="peo"/> -->
        <package name="com.mybatis.po" />
    </typeAliases>
    <!-- 配置mybatis运行环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- MySQL数据库驱动 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <!-- 连接数据库的URL -->
                <property name="url"
                    value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中 -->
    <mappers>
        <package name="com.mybatis.mapper"/>
    </mappers>
</configuration>
mybatis.xml

com.mybatis.util包

package com.mybatis.util;

import java.io.IOException;
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;

public class MybatisUtil {
    
    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> tl=new ThreadLocal<SqlSession>();
    static{
        try {
            InputStream is=Resources.getResourceAsStream("mybatis.xml");
            factory=new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
    
    public static SqlSession getsSession() {
        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);
    }
}
MybatisUtil.java

com.mybatis.filter包

package com.mybatis.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.apache.ibatis.session.SqlSession;

import com.mybatis.util.MybatisUtil;

@WebFilter("/*")
public class OpenSessionInView implements Filter{

    @Override
    public void destroy() {
        // TODO 自动生成的方法存根
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        SqlSession session=MybatisUtil.getsSession();
        try {
            chain.doFilter(request, response);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        }finally {
            MybatisUtil.closeSession();
        }
        
        
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO 自动生成的方法存根
        
    }
}
OpenSessionInView.java

com.mybatis.po包

package com.mybatis.po;

public class Teachar {
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    
}
Teachar.java
package com.mybatis.po;

public class Student {
    private int id;
    private String name;
    private int age;
    private int tid;
    private Teachar teachar;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getTid() {
        return tid;
    }
    public void setTid(int tid) {
        this.tid = tid;
    }
    public Teachar getTeachar() {
        return teachar;
    }
    public void setTeachar(Teachar teachar) {
        this.teachar = teachar;
    }
    
    
}
Student.java
package com.mybatis.po;

import java.util.List;

public class PageInfo {
    //每个分页显示的条数
    private int pageSize;
    //当前是第几页
    private int pageNumber;
    //总页数
    private long total;
    private List<?> list;
    //学生姓名
    private String sname;
    //老师姓名
    private String tname;
    //已查过前几条
    private int pageStart;
    
    
    public int getPageStart() {
        return pageStart;
    }
    public void setPageStart(int pageStart) {
        this.pageStart = pageStart;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getPageNumber() {
        return pageNumber;
    }
    public void setPageNumber(int pageNumber) {
        this.pageNumber = pageNumber;
    }
    public long getTotal() {
        return total;
    }
    public void setTotal(long total) {
        我是如何自学编程以及如何两个月达到一万粉丝的,辣条的心路历程希望能帮助到你

Himi浅谈游戏开发de自学历程!(仅供参考)

大神从自学到跟班学习的艰辛历程

新手小白自学hibernate,官方文档错误,导致的坑爹历程

渗透测试自学系列— 网络攻防技术演化历程

在读学生自学Ubuntu20.04用C++调用matplotlib历程