MyBatis配置以及执行小例子

这是我第一次写日志,有什么不妥的用词,请大家指出来哈!
今天自学了个框架MyBatis,郁闷了一天,insert怎么都不在数据库生成记录,最后发现原来是没有commit。。。
以下是我的第一个MyBatis Project。

试验项目总体结构


1.src目录下配置configuration.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/mybatis?useUnicode=true&amp;characterEncoding=GBK"/>
<property name="username" value="root"/>
<property name="password" value="1989"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/olive/entityconfig/Person.xml"/>
</mappers>
</configuration>

2.建立实体类com.olive.entity.Person
    ...
    private long id;
    private String username;
    private String password;
    ...
    getter,setter...
    ...

3.建立Person的Mapper文件com.olive.entityconfig.Person.xml
<?xml version="1.0" encoding="UTF-8" ?>    
<!DOCTYPE mapper    
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"    
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> 

<mapper namespace="com.olive.entity.PersonMapper">
    <insert id="insertPerson" parameterType="com.olive.entity.Person" useGeneratedKeys="true">
insert into person (id,name,age,sex) values(#{id},#{name},#{age},#{sex});
</insert>
</mapper>

*注:useGeneratedKeys="true",自动生成主键

4.建立SqlSessionFactory生成工具类com.olive.util.Util

public class Util {

private static SqlSessionFactory sqlSessionFactory = null;

static{
String resource = "configuration.xml";

Reader reader = null;

try {
reader = Resources.getResourceAsReader(resource);
} catch (Exception e) {
e.printStackTrace();
}

sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}

public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}

5.建立Dao类com.olive.dao.PersonDao

public class PersonDao {
public String insert(Person person){
SqlSession sqlSession = Util.getSqlSessionFactory().openSession(true);
int result = 0;
System.out.println(person);
try{
result = sqlSession.insert("com.olive.entity.PersonMapper.insertPerson", person);
}catch (Exception e) {
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultAnalyze(result);
}
}

*注:.openSession(true)表示事务自动commit,这在进行DML(insert,update,delete)操作时候使用,进行DQL(select)则不需要autoCommit参数。

6.调用实例
                ......
person = new Person();
person.setName("Nevol");
person.setSex("男");
person.setAge(22);
String result = personDao.insert(person);
System.out.println(result);
                ......

另外,src/log4j.xml中配置实现控制台输出SQL语句。


猜你喜欢

转载自huangyijie.iteye.com/blog/1346799