学习Mybatis(1):独立使用

1.编写配置文件:

这里取名为:mybatis_config.xml,放在resource目录下(classpath)

<?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>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"></setting>
        <setting name="aggressiveLazyLoading" value="false"></setting>
        <setting name="cacheEnabled" value="true"></setting>
    </settings>
    //JDBC配置,可以有多份(对应生产环境、开发环境、测试环境等),使用default属性切换
    <environments default="dev">
        <environment id="dev">
            //事务管理器
            <transactionManager type="JDBC"/>
            //数据源,这里配置为连接池
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        //以下三个配置等效
        <mapper class="mybatis.UserService"/>
        <!--mapper resource="mybatis\UserService.xml"/-->
        <!--mapper package="mybatis"/-->
    </mappers>
</configuration>

mapper处的配置,在本例中,三种效果一样

第一种:配置mapper接口(这里是mybatis.UserService,mybatis会在resource的mybatis路径下查找同名xml文件)

第二种:配置mapper文件:xml文件需要放在classpath下

第三种:配置mapper所在的包:会自动扫描下面所有的mapper和classpath同名文件夹下所有xml

配置详见:Mybatis XML配置

2.java类编写

UserService接口:

package mybatis;

public interface UserService {
    User getUser(int id);
}

User是一个POJO类:

package mybatis;

public class User {
    int id;
    String userName;
    int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

3.映射配置:

UserService.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">
<mapper namespace="mybatis.UserService">
    <select id="getUser" resultType="mybatis.User" parameterType="int">
        select * from User where id=#{id};
    </select>
</mapper>

namespace:对应的Mapper接口

select标签:对应select方法,其他标签还有insert、update、delete等

id:就是对应的方法名

resultType:方法对应的返回值类型,如果是Java包装类,需要写全路径,如:java.lang.String

parameterType:和resultType一样

配置详见:Mybatis XML 映射文件

4.测试:

Mybatis需要通过SqlSession发起请求,并提供了生产SqlSession对象的工厂类SqlSessionFactory

public static void main(String[] args) throws IOException {
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis_config.xml"));
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserService userMapper=sqlSession.getMapper(UserService.class);
        User user=userMapper.getUser(1);
        System.out.println(user.toString());
}

SqlSessionFactory是一个接口,通过SqlSessionFactoryBuilder生成(实质上是解析配置文件,然后实例化一个DefaultSqlSessionFactory对象),或者自己实现

openSession就是SqlSessionFactory生产SqlSession对象的方法,提供了一些参数:

autoCommit:是否自动提交事务,默认false

ExecutorType:默认SIMPLE

TransactionIsolationLevel:事务隔离级别,默认null

Connection:使用JDBC连接开启会话,从连接中提取上述参数

以上代码输入内容类似:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Wed Nov 21 12:27:33 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.
User{id=1, userName='zhangsan', age=1}

Process finished with exit code 0

5.可能的错误:

1)BindingException:

例如:

Exception in thread "main" org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): mybatis.UserService.getUser
	at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:189)
	at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:43)
	at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:58)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:51)
	at com.sun.proxy.$Proxy0.getUser(Unknown Source)
	at mybatis.MybatisTest.main(MybatisTest.java:15)

可能的原因:

  • 映射配置文件(UserService.xml)不在classpath的mybatis文件夹下
  • 映射文件中没有id为getUser的项
  • 映射配置文件中,id为getUser的项的resultType或parameterType与接口定义不符

2)xml格式问题导致的解析错误

3)数据源配置错误导致的连接失败,如url错误、帐号密码错误

还有数据源url没有配置 useUnicode=true&characterEncoding=utf8 也可能导致中文乱码

猜你喜欢

转载自blog.csdn.net/u010670411/article/details/84317306