MyBatis 配置模板

MyBatis 配置模板

pom.xml 文件配置

Maven 依赖

<!-- 导入依赖 -->
<dependencies>
    <!-- mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <!-- junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
</dependencies>

静态资源过滤问题

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

核心配置文件 mybatis-config.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 核心配置文件 -->
<configuration>
    
    <!--引入外部配置文件-->
    <properties resource="db.properties">
    	<!--<property name="username" value="root"/>-->
    	<!--<property name="password" value="root"/>-->
	</properties>
    
    <settings>
        <!--标准的日志工厂实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--<setting name="logImpl" value="LOG4J"/>-->
        <!--下划线驼峰自动转换-->
    	<setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--显式的开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
    <!--给实体类起别名-->
	<typeAliases>
    	<!--<typeAlias type="com.song.pojo.User" alias="User"/>-->
        <package name="com.song.pojo"/>
	</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>
        
        <environment id="test">
            <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>

    <!-- 每一个 Mapper.XML 都需要在 Mybatis 核心配置文件中注册!!-->
    <mappers>
        <mapper resource="com/song/dao/UserMapper.xml"/>
        <!--<mapper class="com.song.dao.UserMapper"/>-->
        <!--<package name="com.song.dao"/>-->
    </mappers>
</configuration>

数据库配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=root

MyBatis 工具类 MybatisUtils

// SqlSessionFactory --> sqlSession
public class MybatisUtils {

    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 的实例。
    public static SqlSession getSqlSession(){
//        SqlSession sqlSession = sqlSessionFactory.openSession();
//        return sqlSession;
        return sqlSessionFactory.openSession();
        // 使用注解时,要打开自动提交
        // return sqlSessionFactory.openSession(true);
    }
}

实体类的配置文件 UserMapper.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">

<!--namespace = 绑定一个对应的 Dao/Mapper 接口-->
<mapper namespace="com.song.dao.UserDao">
    
    <!--第三方缓存,需要导入资源配置文件-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
    <!--在当前 Mapper.xml 中使用二级缓存-->
    <!--<cache/>-->
    <!--<cache eviction="FIFO"-->
           <!--flushInterval="60000"-->
           <!--size="512"-->
           <!--readOnly="true"/>-->
    

    <!-- select 查询语句,id 绑定方法名,
    返回结果写全限定类名,因为配置文件不会像java类一样会自动找关联,集合都写泛型中的类-->
    <select id="getUserList" resultType="com.song.pojo.User">
        select * from mybatis.user
    </select>
    
    <!--注意:增删改需要提交事务-->
    <insert>......</insert>
    <update>......</update>       
    <delete>......</delete>

    
    <!--引用 resultMap 属性,其中 UserMap 是自己起的名字,不用 resultType 属性-->
    <select id="getUserById" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>
    
    <!--结果集映射,id 和下面 select 标签中 resultMap 的值对应,type 为映射成的类型-->
    <resultMap id="UserMap" type="User">
        <!-- column 数据库中的字段, property 实体类中的属性-->
        <!-- <result column="id" property="id"/> -->
        <!-- <result column="name" property="name"/> -->
        <result column="pwd" property="password"/>
        <!--复杂的属性需要单独处理   
			对象:association 
			集合:collection 
		-->
        <!-- <association property="" .../> -->
        <!-- <collection property="" .../>-->
    </resultMap>
    
    
</mapper>

注解

@Param
@select()
@update()
@Insert()
@delete()

注意:

  • 在工具类 MybatisUtils.class 创建的时候实现自动提交事务。
  • 必须先将接口注册绑定(通过class)到 MyBatis 的核心配置文件中(如果有多个接口,每个接口都要绑定)。

测试类

@Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        
        User user = mapper.getUserById(1);
        System.out.println(user);

        sqlSession.close();
    }

Lombok 插件

Maven 依赖

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
    <scope>provided</scope>
</dependency>

常见注解:

@Data   无参构造 getter setter tostring hashcode equals
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor 有参构造 无参构造
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val

猜你喜欢

转载自www.cnblogs.com/Songzw/p/13170357.html