首先用创建一个java控制台程序,
然后创建一个引入mybatis和MySql的jar包,
再创建一个mybatis的配置文件如mybatis.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>
<typeAliases>
<typeAlias alias="User" type="models.User" />
</typeAliases>
<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://127.0.0.1:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 这个是数据的配置文件,后面会配置 -->
<mapper resource="medels/User.xml" />
</mappers>
</configuration>
再创建一个User类,作为数据模型,
package models;
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
然后给数据模型创建映射文件,这个和mabatis.xml里的 <mapper resource="medels/User.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="models">
<select id="getUserByID" parameterType="int" resultType="User">
select * from `tt` where id = #{id}
</select>
</mapper>
最后是main函数
public class Main {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
public Main() {
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
User user = (User)session.selectOne("getUserByID", Integer.valueOf(1));
if (user != null) {
String userInfo = "名字:" + user.getName() + ", Id:" + user.getId();
System.out.println(userInfo);
}
} finally {
session.close();
}
}
static {
try {
reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = (new SqlSessionFactoryBuilder()).build(reader);
} catch (Exception var1) {
var1.printStackTrace();
}
}
}