1配置环境
1.1配置mvaen
maven 阿里云连接
1.2引入jar
1.2.1mybatis
< dependency>
< groupId> org.mybatis</ groupId>
< artifactId> mybatis</ artifactId>
< version> 3.5.1</ version>
</ dependency>
1.2.2mysql
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 5.1.41</ version>
</ dependency>
1.3在resource下创建 mymybatis 配置文件 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.jdbc.Driver" />
< property name = " url" value = " jdbc:mysql://localhost:3306/lsq" />
< property name = " username" value = " root" />
< property name = " password" value = " 111111" />
</ dataSource>
</ environment>
</ environments>
< mappers>
< mapper resource = " sql.xml" />
</ mappers>
</ configuration>
1.4 在resource下配置 sql mapper文件
<?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 = " sql" >
< select id = " getUser" parameterType = " int" resultType = " bean.User" >
select * from user where id = #{id}
</ select>
</ mapper>
1.5 创建bean 在包bean下创建 user
package bean;
public class User {
private String id;
private String name;
private String pass;
public User ( String id, String name, String pass) {
super ( ) ;
this . id = id;
this . name = name;
this . pass = pass;
}
public User ( ) {
super ( ) ;
}
public String getId ( ) {
return id;
}
public void setId ( String id) {
this . id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public String getPass ( ) {
return pass;
}
public void setPass ( String pass) {
this . pass = pass;
}
@Override
public String toString ( ) {
return "User [id=" + id + ", name=" + name + ", pass=" + pass + ", getId()=" + getId ( ) + ", getName()="
+ getName ( ) + ", getPass()=" + getPass ( ) + ", getClass()=" + getClass ( ) + ", hashCode()=" + hashCode ( )
+ ", toString()=" + super . toString ( ) + "]" ;
}
}
1.6 调用
String resource = "conf.xml" ;
Reader reader = null;
try {
reader = Resources. getResourceAsReader ( resource) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder ( ) . build ( reader) ;
SqlSession session = sessionFactory. openSession ( ) ;
String statement = "sql.getUser" ;
User user = session. selectOne ( statement, 4 ) ;
System. out. println ( user) ;