HelloWorld之MyBatis
项目的目录结构:
很简单。Account是要组装的Domain对象,AccountDAO是测试类,
mapper/Account.xml保存了两条Account的查询语句,而mybatis.cfg.xml
是数据库连接的配置。
package com.cdai.orm.mybatis; public class Account { private long id; private long balance; public Account() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getBalance() { return balance; } public void setBalance(long balance) { this.balance = balance; } @Override public String toString() { return "Account [id=" + id + ", balance=" + balance + "]"; } }
<?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="Account" type="com.cdai.orm.mybatis.Account" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="url" value="jdbc:sqlserver://192.168.1.102:1433;databaseName=Bank" /> <property name="username" value="sa" /> <property name="password" value="1qaz2wsx" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/Account.xml" /> </mappers> </configuration>
<?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="Account"> <select id="selectAccount" parameterType="int" resultType="Account"> <![CDATA[ SELECT col_id AS id, col_balance AS balance FROM tb_account ]]> </select> <select id="selectAccountById" parameterType="int" resultType="Account"> <![CDATA[ SELECT col_id AS id, col_balance AS balance FROM tb_account WHERE col_id = #{id} ]]> </select> </mapper>
package com.cdai.orm.mybatis; import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class AccountDAO { @SuppressWarnings("unchecked") public static void main(String[] args) { String resource = "mybatis.cfg.xml"; try { Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sessionFactory.openSession(); List<Account> accounts = (List<Account>) session.selectList("selectAccount"); for (Account account : accounts) { System.out.println(account); } Account account = (Account) session.selectOne("selectAccountById", 2); System.out.println(account); session.close(); } catch (IOException e) { e.printStackTrace(); } } }