mybatis

本文档详细介绍了如何创建一个 MyBatis Maven 工程,包括配置 `pom.xml` 文件,设置数据库连接信息,编写 `mybatis-config.xml` 配置文件,创建 Mapper 接口及 XML 映射文件,并展示了如何在 Java 测试类中使用 MyBatis 进行 CRUD 操作。此外,还提到了外部化配置、静态工厂方法封装以及 JUnit 测试用例。
摘要由CSDN通过智能技术生成

一.创建maven工程
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-demo1</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
</project>
<?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="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/my?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers\StudentMapper.xml"></mapper>
    </mappers>
</configuration>
<?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="org.mybatis.dao.StudentInterface">
    <insert id="insertStudent">
        insert into s1(ename,jod_id,mgr,salary,bouns,dept_id) values (#{ename},#{jod_id},#{mgr},#{salary},#{bouns},#{dept_id})
    </insert>
    <delete id="deleteStudent">
        delete from s1 where ename=#{ename};
    </delete>
    <update id="UpdateStudent">
        update s1 set bouns=#{bouns} where ename=#{ename}
    </update>
</mapper>
public class Student {
    private String ename;
    private int jod_id;
    private int mgr;
    private double salary;
    private double bouns;
    private int dept_id;


    public Student(String ygl, int i, int i1, double v, double v1, int i2) {
    ename=ygl;jod_id=i;mgr=i1;salary=v;bouns=v1;dept_id=i2;

    }


}
import org.mybatis.Student.Student;

public interface StudentInterface {
    public int insertStudent(Student student);
	public int deleteStudent(String ename);
    public int UpdateStudent(@Param("bouns") double bouns,@Param("ename") String ename);
}

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.Student.Student;
import java.io.IOException;
import java.io.InputStream;

public class StudentInterfaceTest {
    @org.junit.Test
    public void testInsertStudent() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");//获取mybatis-config.xml文件
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(inputStream);//初始化mybatis,创建SqlSessionFactory类的实例
        SqlSession session = sqlSessionFactory.openSession();//创建Session实例
        StudentInterface studentInterface = session.getMapper(StudentInterface.class);
        int i = studentInterface.insertStudent(new Student("ygl", 1, 6,66666.6, 66666.6, 7));
        System.out.println(i);
        session.commit();//提交事务
        session.close();
    }

@org.junit.Test
    public void testDeleteStudent() throws IOException{
        InputStream read=Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(read);
        SqlSession session = build.openSession();
        StudentInterface mapper = session.getMapper(StudentInterface.class);
        int i=mapper.deleteStudent("ygl");
        try{
            assertEquals(1,i);
        }
        catch(Exception e){
            e.printStackTrace();
        }finally{
            session.commit();
            System.out.println("1111111");
            session.close();
        }
    }
@org.junit.Test
    public void UpdateStudent() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession session = sqlSessionFactory.openSession();
        StudentInterface mapper = session.getMapper(StudentInterface.class);
        int i=mapper.UpdateStudent(100000.0,"k");
        session.commit();
        try{
        assertEquals(1,i);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            session.close();
        }
    }
}

在这里插入图片描述
properties属性
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可以通过properties元素的子元素来传递。
可以在CLASSPATH中增加一个db.properties的Java属性文件。
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis
username=root
password=root
在配置文件中配置<properties…/>属性:

<properties resources="db.properties"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>

封装类

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
public class fengzhuang {
    private static SqlSession sqlSession=null;
    static{
        try {
            InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getsqlSession(){

        return sqlSession;
    }
}
@org.junit.Test
    public void testInsertStudent() throws IOException {
        StudentInterface studentInterface = fengzhuang.getsqlSession().getMapper(StudentInterface.class);
        int i = studentInterface.insertStudent(new Student("ghjklp", 1, 9,996666.6, 996666.6, 8));
        System.out.println(i);
        fengzhuang.getsqlSession().commit();
        fengzhuang.getsqlSession().close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值