A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 逆风TO 于 2020-3-10 14:28 编辑

Mybatis的整体环境搭建(呕血总结:绝对细致)总体布局:
第一步:编写javabean代码 :这里不必赘述

补充:成员变量名最好要与数据库字段保持一致,如果没有执行sql语句会执行不顺利(有解决办法,往后看)

[Java] 纯文本查看 复制代码
public class User {
    private int id;
    private String name;
    private String password;//这里我没有和数据库字段保持一致,我后面用了resultMap做了处理
    
    public User() {
    }
    public User(int id){
        this.id = id;
    }

    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

第二步:配置maven环境,导入必需的jar包
[Java] 纯文本查看 复制代码
<?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 [url=http://maven.apache.org/xsd/maven-4.0.0.xsd]http://maven.apache.org/xsd/maven-4.0.0.xsd[/url]">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wang</groupId>
    <artifactId>Mybatis_02</artifactId>
    <version>1.0-SNAPSHOT</version>
 <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>8.0.17</version>
     </dependency>
     <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis</artifactId>
         <version>3.5.2</version>
     </dependency>
     <dependency>
         <groupId>log4j</groupId>
         <artifactId>log4j</artifactId>
         <version>1.2.17</version>
     </dependency>
 </dependencies>

    <!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

第三步:1.配置核心配置文件 mybatis-config.xml
[Java] 纯文本查看 复制代码
<?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>
    <!--引入外部配置文件-->
    <properties resource="db.properties"/>
    <settings>
        <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.wang.domain.User" alias="User"/>
    </typeAliases>
    <!--<typeAliases>
        <package name="com.wang.domain"/>
    </typeAliases>-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/wang/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

这里需要特别注意:SAXParseException异常:是因为我们的定义内容顺序不对:应该是properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?的顺序

2.创建db.properties 配置文件
这里我的用户和密码都是root (根据自己的修改)
[Java] 纯文本查看 复制代码
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=root

第四步:定义工具类
[Java] 纯文本查看 复制代码
package com.wang.utils;

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 MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try{
            //使用mybatis第一步、获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

    //既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
    // SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
    // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

第五步:1.创建功能接口(在这里我简单定义了两个功能)
[Java] 纯文本查看 复制代码
public interface UserMapper {
    List<User> getUserList();
    User getUserById(int id);
    void insterUser(Map<String,Object> m);
}

2.定义功能接口的实现xml文件

注意:在这里我对前面数据库字段和成员属性的名称不同的情况进行了解决

[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.wang.mapper.UserMapper">
    <resultMap id="UserMap" type="User">
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="getUserList" resultType="User">
        select id,name,pwd as password from user
    </select>
    <select id="getUserById" resultMap="UserMap" parameterType="_int">
        select  * from user where id = ${id}
    </select>
    <insert id="insterUser" parameterType="map">
        insert into user (id,name,pwd) values(#{userId},#{userName},#{password})
    </insert>
</mapper>

第六步 : 导入log4j.properties日志配置文件
[Java] 纯文本查看 复制代码
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=./log/wang.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

最后:进行测试

这里我们习惯将测试类放入和功能接口一样的包中

[Java] 纯文本查看 复制代码
package com.wang.mapper;

        import com.wang.domain.User;
        import com.wang.utils.MybatisUtil;
        import org.apache.ibatis.session.SqlSession;
        import org.apache.log4j.Logger;
        import org.junit.Test;

        import java.util.HashMap;
        import java.util.List;


public class MybatisTest {
    static Logger logger = Logger.getLogger(MybatisTest.class);
    @Test
    public void getuserList(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        /*logger.info("info:进入了testLog4j方法");
        logger.debug("debug:进入了testLog4j");
        logger.error("error:进入了testLog4j");*/
        User userById = mapper.getUserById(1);
        System.out.println(userById);
        sqlSession.close();
    }
    @Test
    public void insertUser(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String,Object> m = new HashMap<String,Object>();
        m.put("userId",5);
        m.put("userName","王五");
        m.put("password","23333");
        mapper.insterUser(m);
        sqlSession.commit();
        sqlSession.close();
    }
}






0 个回复

您需要登录后才可以回帖 登录 | 加入黑马