mybatis(1):maven下完成配置,进行一次查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41376740/article/details/82880085

前言

基于对mybatis的崇拜,我开始了第一次的配置,代码就开始写了起来。

一款好用的插件: Mybatis plugin

  • 安装:在IDEA 的插件安装即可安装
    在这里插入图片描述

它的功能如下:https://blog.csdn.net/yangshijin1988/article/details/63258960 ,可以生成配置文件,自动映射mapper.xml文件等。还是很好用的哦~

重要分割线: 原来这个上面的插件需要钱,再想办法破解我觉得太麻烦了,于是乎就下载了下面的免费mybatis插件:就是上面的Free Mybatis Plugin,下面我会在我的例子中演示基本的使用

配置文件

第一步: 做自己的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>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="false"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="5"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
</configuration>

第二步: 配连接池:我的mysql connector版本8.0.12

<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/blog"/>
                <property name="username" value="xxxx"/>
                <property name="password" value="xxxx"/>
            </dataSource>
        </environment>
    </environments>

设置mapper映射

public interface UserMapper {

    User getUser(int id);

}

选中UserMapper alt+enter,自动生成mapper映射xml文件
在这里插入图片描述
之后输入你的sql语句,如果没有提示,你需要绑定你的数据源。百度:IDEA 绑定数据源

<?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="mapper.UserMapper">
    <select id="getUser" resultType="bean.User">
        select
            user_name,
            user_age
        from user
        where user_id = #{id}
    </select>
</mapper>

再在原来的mybatis-config里面配置mapper映射:

<mappers>
        <mapper resource="mybatis/userMapper.xml"/>
</mappers>

配置log4j2

文件名要写成log4j2.properties

status = error
name = PropertiesConfig

filters = threshold

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appenders = console

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

编写测试代码

工具类

public class SqlSessionFactoryUtils {

    private static SqlSessionFactory factory = null;
    private static final Logger LOGGER = LogManager.getLogger(SqlSessionFactoryUtils.class.getName());

    static {
        String xmlConfig = "mybatis/mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(xmlConfig);
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            LOGGER.error("处错误了", e);
        }
    }

    public static SqlSession openSqlSession() {
        return factory.openSession();
    }
}
public static void main(String[] args) {
        SqlSession sqlSession = SqlSessionFactoryUtils.openSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUser(1);
        System.out.println(user);
        sqlSession.close();
    }
output:
Connected to the target VM, address: '127.0.0.1:34779', transport: 'socket'
2018-09-28 12:09:00 DEBUG LogFactory:54 - Logging initialized using 'class org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl' adapter.
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector (file:/home/dream/apache-maven-3.5.4/maven_local_repository/org/mybatis/mybatis/3.4.6/mybatis-3.4.6.jar) to method java.lang.Class.checkPackageAccess(java.lang.SecurityManager,java.lang.ClassLoader,boolean)
WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2018-09-28 12:09:01 DEBUG PooledDataSource:54 - PooledDataSource forcefully closed/removed all connections.
2018-09-28 12:09:01 DEBUG PooledDataSource:54 - PooledDataSource forcefully closed/removed all connections.
2018-09-28 12:09:01 DEBUG PooledDataSource:54 - PooledDataSource forcefully closed/removed all connections.
2018-09-28 12:09:01 DEBUG PooledDataSource:54 - PooledDataSource forcefully closed/removed all connections.
2018-09-28 12:09:01 DEBUG JdbcTransaction:54 - Opening JDBC Connection
Fri Sep 28 12:09:02 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-09-28 12:09:02 DEBUG PooledDataSource:54 - Created connection 248483913.
2018-09-28 12:09:02 DEBUG JdbcTransaction:54 - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@ecf9049]
2018-09-28 12:09:02 DEBUG getUser:54 - ==>  Preparing: select user_name, user_age from user where user_id = ? 
2018-09-28 12:09:02 DEBUG getUser:54 - ==> Parameters: 1(Integer)
2018-09-28 12:09:02 DEBUG getUser:54 - <==      Total: 1
User{userName='肖鑫', userAge=21}
2018-09-28 12:09:02 DEBUG JdbcTransaction:54 - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@ecf9049]
2018-09-28 12:09:02 DEBUG JdbcTransaction:54 - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@ecf9049]
2018-09-28 12:09:02 DEBUG PooledDataSource:54 - Returned connection 248483913 to pool.

可能出现的问题

1、xx.xml文件未找到。
maven 打包的时候不会打包一些文件。在pom.xml的build节点中添加下面的:意思就是说,你打包的时候帮我把这些文件也带上吧。

<resources>
            <resource>
                <directory>src/main/resource</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>*.properties</include>
                </includes>
            </resource>
        </resources>

2、log4j消息打印不出来,显示没有找到对应的properties文件。
注意log4j2的命名,properties文件的命名要写成log4j2有一个2。

结语

学习的路很长,加油~

猜你喜欢

转载自blog.csdn.net/qq_41376740/article/details/82880085