mybatis入门及配置注意事项

整体结构
mybatis入门及配置注意事项_第1张图片

sqlMapConfig.xml


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="jdbc">transactionManager> 
            <dataSource type="POOLED">

                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/wsp?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource> 
        environment>
    environments>


    
    <mappers>
        
        <mapper resource="com/wsp/dao/userDao.xml"/>
    mappers>
configuration>

userDao.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.wsp.dao.userDao">
    

    <select id="findAll" resultType="com.wsp.domain.user">
        select * from user
    select>
mapper>

配置要注意的几点

  1. mybatis的映射配置文件位置必须和dao接口的包结构一致
  2. 映射配置文件的mapper标签的namespace属性取值必须是dao接口的全限定类名 (为了区分不同dao同名的方法)
  3. 映射文件的配置操作 id属性要与dao方法名一致

遵从以上三点 无需再写dao实现类
mybatisTest

package test;


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 com.wsp.dao.userDao;
import com.wsp.domain.user;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {
    public static void main(String[] args) throws IOException {
        //读取配置文件
        InputStream in= Resources.getResourceAsStream("sqlMapConfig.xml");
        //创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory factory=builder.build(in);
        //生产sqlSession对象
        SqlSession session= factory.openSession();
        //创建dao接口的代理对象
        userDao userDao=session.getMapper(userDao.class);


        List<user> list=userDao.findAll();
        for(user user:list){
            System.out.println(user);
        }

        session.close();
        in.close();
    }
}

mybatis入门及配置注意事项_第2张图片
mybatis入门及配置注意事项_第3张图片

你可能感兴趣的:(java框架,java,后端)