一、引入MyBatis依赖
< dependency>
< groupId> org.mybatis</ groupId>
< artifactId> mybatis</ artifactId>
< version> 3.4.6</ version>
</ dependency>
二、新建实体类User
package com. mybatisdemo. demo1. entity;
import lombok. Data;
@Data
public class User {
private String name;
private Integer age;
}
三、编写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" >
< mapper namespace = " com.mybatis.demo1.mapper.UserMapper" >
< select id = " findUserByName" resultType = " com.mybatisdemo.demo1.entity.User" parameterType = " java.lang.String" >
SELECT NAME,AGE FROM USER WHERE NAME = #{name}
</ select>
</ mapper>
四、编写配置文件conf.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>
< 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/springdb?useUnicode=true& characterEncoding=utf8& serverTimezone=GMT%2B8& useSSL=false" />
< property name = " username" value = " root" />
< property name = " password" value = " root" />
</ dataSource>
</ environment>
</ environments>
< mappers>
< mapper resource = " mybatis.mapper\UserMapper.xml" />
</ mappers>
</ configuration>
五、编写测试代码
package com. mybatisdemo. demo1;
import com. mybatisdemo. demo1. entity. User;
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 MyBatisApp {
public static void main ( String[ ] args) throws IOException {
String resource = "mybatis.mapper/conf.xml" ;
InputStream inputStream = Resources. getResourceAsStream ( resource) ;
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder ( ) . build ( inputStream) ;
SqlSession sqlSession = sessionFactory. openSession ( ) ;
User user = sqlSession. selectOne ( "com.mybatis.demo1.mapper.UserMapper.findUserByName" , "xiaoming" ) ;
sqlSession. close ( ) ;
System. out. println ( user. toString ( ) ) ;
}
}
六、运行测试代码
七、工程目录结构