下載app免費(fèi)領(lǐng)取會員
首先用創(chuàng)建一個java控制臺程序,
然后創(chuàng)建一個引入mybatis和MySql的jar包,
再創(chuàng)建一個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>
<!-- 這個是數(shù)據(jù)的配置文件,后面會配置 -->
<mapper resource="medels/User.xml" />
</mappers>
</configuration>
再創(chuàng)建一個User類,作為數(shù)據(jù)模型,
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;
}
}
然后給數(shù)據(jù)模型創(chuàng)建映射文件,這個和mabatis.xml里的 <mapper resource="medels/User.xml" /> 是對應(yīng)的
<?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函數(shù)
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();
}
}
}
本文版權(quán)歸腿腿教學(xué)網(wǎng)及原創(chuàng)作者所有,未經(jīng)授權(quán),謝絕轉(zhuǎn)載。
下一篇:二次開發(fā)教程:Revit開發(fā)IExternalCommandAvailability的使用
推薦專題