一个简单的mybatis入门demo

创一个简单的maven项目

第一步:maven配置

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>

第二步:实体和DAO接口

实体类

public class FundBase {
/**
* 基金代码
*/
private int code;
/**
* 基金名称
*/
private String name;
/**
* 成立日期
*/
private Date foundedTime;
/**
* 记录保存时间
*/
private Date saveTime;


public int getCode() {
return code;
}


public void setCode(int code) {
this.code = code;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public Date getFoundedTime() {
return foundedTime;
}


public void setFoundedTime(Date foundedTime) {
this.foundedTime = foundedTime;
}


public Date getSaveTime() {
return saveTime;
}


public void setSaveTime(Date saveTime) {
this.saveTime = saveTime;
}


}

DAO接口

public interface FundBaseDao {
public List<FundBase> queryAllFundBase();
public FundBase queryFundBaseByCode();
}

第三部:配置文件

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 type="com.chenyun.fund.dao.FundBaseDao" alias="FundBaseDao" />
<typeAlias type="com.chenyun.fund.dao.FundBase" alias="FundBase" />
</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://192.168.1.200:3306/fund?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="chenyun" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="FundBaseDao.xml" />
</mappers>


</configuration> 

FundBaseDao.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.chenyun.fund.dao.FundBaseDao">
<select id="queryAllFundBase" resultType="FundBase" useCache="true">  
        <![CDATA[ 
        select * from FundBase 
        ]]>
</select>
</mapper>  

第四部:测试

public static void main(String[] args) {
String resource = "mybatis.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
.build(reader);
SqlSession session = sessionFactory.openSession();
FundBaseDao userDao = session.getMapper(FundBaseDao.class);
List<FundBase> users = userDao.queryAllFundBase();
for (FundBase fund : users) {
System.out.println(fund.getCode() + ":" + fund.getName());
}
}

你可能感兴趣的:(一个简单的mybatis入门demo)