- 下载mybatis.zip,解压
- 新建java工程
- 导入jar包 (记得需要右键build path)
4.建立数据库以及建表
5. 在工程中加入mybatis-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/blog" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
6.编写实体类User
package com.user.mysql;
public class User {
private int id;
private String username;
private String password;
private String phone;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
7.编写映射文件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="usermapper">
<!-- parameterType表示参数类型
resultType表示结果类型 -->
<select id="getUser" parameterType="int" resultType="com.user.mysql.User">
<!-- 注意这里是真正的sql,#{}作为参数的占位符 -->
select * from users where id = #{id}
</select>
</mapper>
8.在主配置中加入mapper (与environments同级)
<mappers>
<mapper resource="com/user/mysql/UserMapper.xml" />
</mappers>
9. 编写测试类
package com.user.test;
import java.io.IOException;
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.user.mysql.User;
public class Test {
public static void main(String[] args) {
//创建SqlSessionFactory
SqlSessionFactory factory;
try {
factory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("mybatis-conf.xml"));
SqlSession session = factory.openSession();
String statment = "usermapper.getUser"; //等于mapper的namespace+具体sql的id
//参数表示获取表中第几列数
User user = session.selectOne(statment, 1);
//打印的是表中什么字段的内容
System.out.println(user.getUsername());
} catch (IOException e) {
e.printStackTrace();
}
}
}
工程下的部署
第一次学mybatis的框架,相比原来写的代码连接数据库之类的更加灵活应用
MyBatis是一个数据持久层(ORM)框架,在实体类和SQL语句之间建立映射关系,是一种半自动化的ORM实现。
MyBatis的优点:
1、基于SQL语法,简单易学。
2、能了解底层组装过程。
3、SQL语句封装在配置文件中,便于统一管理与维护,降低了程序的耦合度。
4、程序调试方便。