欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

derby+myBatis 入门

程序员文章站 2022-07-15 14:35:51
...

1, 下载derby, myBatis。

2, 设定DERBY_HOME环境变量和PATH环境变量。

3, 用ij命令执行下面的代码。

connect 'jdbc:derby:tianyuDB;create=true';
create table Person (id int primary);
insert into Persion values (1);
disconnect;

4,写JavaBean

package examples.main;

public class Person {

    private String name;

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

    public String getName() {
        return name;
    }

}

5,读取配置文件,取得SqlSessionFactory

package examples.main;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyAppSqlConfig {

    private static final SqlSessionFactory sqlMap;
    static {
        try {
            String resource = "examples/sqlmap/maps/sqlMapConfig.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            sqlMap = new SqlSessionFactoryBuilder().build(reader);
        }
        catch (Exception e) {
            e.printStackTrace(); 
        }
    }

    public static SqlSessionFactory getSqlMapInstance() {
        return sqlMap;
    }
}

6, SqlSession生成,执行SQL

package examples.main;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class TestMyAppSqlConfig {

    public static void main(String[] args) {
        SqlSessionFactory sqlMapper = MyAppSqlConfig.getSqlMapInstance();

        SqlSession session = sqlMapper.openSession();
        try {
            System.out.println(session.selectOne("selectId"));
        }
        finally {
            session.close();
        }
    }
}

7, 编写 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="org.apache.derby.jdbc.EmbeddedDriver" />
				<property name="url" value="jdbc:derby:tianyuDB;create=true" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="examples/sqlmap/maps/Person.xml" />
	</mappers>
</configuration>

8, 编写 mapper 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="examples.main.Cat">
	<select id="selectId" resultType="Integer">
		select * from Person
	</select>
</mapper>

9, 至此全部结束。可以运行试验一下啦。

 

10, 可以 google code 的这个地址。

  http://javamp3player.googlecode.com/svn/study_derby/