mybatis强化(一)基本配置补充
本文继续最基本案例,使用了mapper接口的注解定义方式。转载注明出处:http://www.cnblogs.com/wdfwolf3/p/6797133.html,谢谢。文件目录如下,
1.配置文件mybatisconfig.xml如下,标红一行和常见设置不同,用来去除警告:Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.原来的类名已经去除,现在使用新的名称。
<?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="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/mybatis?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="1234" /> </dataSource> </environment> </environments> <mappers> <mapper class="com.practice.mapper.UsersMapper"/> </mappers> </configuration>
2.Test测试函数如下,相关问题在前一篇文章中已讲
package com.practice.Test; import com.practice.bean.Users; import com.practice.mapper.UsersMapper;
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 Test2 { public static void main(String[] args) throws IOException { String resource = "mybatisconfig.xml"; InputStream is = Resources.getResourceAsStream(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession(); UsersMapper mapper = session.getMapper(UsersMapper.class); Users user = mapper.getByName("瓦房店"); session.close(); System.out.println(user.getId()); } }
p.s.
如果使用IDEA每次运行都报:Warning:java: 源值1.5已过时, 将在未来所有发行版中删除,Warning:java: 目标值1.5已过时, 将在未来所有发行版中删除,
Warning:java: 要隐藏有关已过时选项的警告, 请使用 -Xlint:-options。
除了改配置,将默认改为1.8编译。还可以在pom.xml文件中加入如下语句解决
<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>