1:通过java代码
package org.mybatis.dao; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import org.mybatis.entity.GameServer; import org.mybatis.mapper.GameServerMapper; /** * SqlSessionFactoryBuilder:这个类可以被实例化,使用和丢弃。一旦你创建了SqlSessionFactory后,这个类就不需要存在了。 * 因此SqlSessionFactoryBuilder实例的最佳范围是方法范围(也就是本地方法变量)。 * 可以重用SqlSessionFactoryBuilder来创建多个SqlSessionFactory实例 * SqlSessionFactory:SqlSessionFactory的最佳范围是应用范围。可以通过单利,静态方法,容器注入等方式实现 * SqlSession:每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能被共享,也是线程不安全的 * Mapper:映射器接口的实例可以从SqlSession中获得。那么从技术上来说,当被请求时,任意映射器实例的最宽范围和SqlSession是相同的。 * 然而,映射器实例的最佳范围是方法范围。也就是说,它们应该在使用它们的方法中被请求,然后就抛弃掉。它们不需要明确地关闭 * @ClassName: MyBatisDao * @Description: * @author */ public class MyBatisDao { private static final String driver = "oracle.jdbc.driver.OracleDriver"; private static final String url = "jdbc:oracle:thin:@ip:port:database"; private static final String userName = "XXX"; private static final String password = "XXX"; private static final SqlSessionFactory sessionFactory; static { DataSource dataSource = new PooledDataSource(driver, url, userName, password); TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration config = new Configuration(environment); config.addMappers("org.mybatis.mapper"); sessionFactory = new SqlSessionFactoryBuilder().build(config); } public SqlSession getSqlSession() { return sessionFactory.openSession(); } //通过这种方式操作数据库,对应的Mapper接口仍然是必须得 public void queryBySession() { SqlSession session = sessionFactory.openSession(); List<GameServer> ss = session.selectList("org.mybatis.mapper.GameServerMapper.getAllGames"); System.out.println(ss.size()); List<GameServer> server = session.selectOne("org.mybatis.mapper.GameServerMapper.getGamePartition",null); System.out.println(server==null); session.close(); } private void queryByMapper() { SqlSession session = sessionFactory.openSession(); GameServerMapper mapper = session.getMapper(GameServerMapper.class); List<GameServer> list = mapper.getAllGames(); System.out.println(list.size()); List<GameServer> list2 = mapper.getGamePartition(null); System.out.println(list2==null); session.close(); } public static void main(String[] args) throws SQLException, ClassNotFoundException { MyBatisDao dao = new MyBatisDao(); dao.queryBySession(); dao.queryByMapper(); } }
package org.mybatis.mapper; import java.util.List; import org.apache.ibatis.annotations.Select; import org.mybatis.entity.GameServer; public interface GameServerMapper { /** * 注解方式不适合于复杂的语句 * @Title: getGameInfo * @Description: * @return */ @Select("SELECT ID,NAME FROM GAME_SERVER WHERE PID=0 ORDER BY ID DESC") List<GameServer> getAllGames(); /** * @Title: getGamePartition * @Description: * @param gameId * @return */ List<GameServer> getGamePartition(Long gameId); }
<?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"> <!-- namespace必须是完整的包名加类型 --> <mapper namespace="org.mybatis.mapper.GameServerMapper"> <!-- 如果没有定义别名,这里的resultType必须使用完整的包名加类名 --> <!-- <select id="getAllGames" resultType="org.mybatis.entity.GameServer"> <![CDATA[ SELECT ID,NAME FROM GAME_SERVER WHERE PID=0 ORDER BY ID DESC ]]> </select> --> <!-- #{}条件通过指定第二个参数jdbcType,在传入的参数为空时也能正常执行;同样适用于insert操作 --> <select id="getGamePartition" parameterType="java.lang.Long" resultType="org.mybatis.entity.GameServer"> <![CDATA[ SELECT ID,NAME FROM GAME_SERVER WHERE PID=#{gameId,jdbcType=NUMERIC} ORDER BY ID DESC ]]> </select> </mapper>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.pps</groupId> <artifactId>mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <dependency> <groupId>ojdbc</groupId> <artifactId>ojdbc</artifactId> <version>14</version> </dependency> </dependencies> </project> 2:通过配置文件 <?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> <!-- 定义属性并指定属性文件 --> <properties resource="jdbc.properties"> <property name="username" value="GCWO_DEV"/> <property name="password" value="GCWO_DEV"/> </properties> <environments default="development"> <environment id="develop"> <!-- 1:JDBC直接依赖JDBC的提交和回滚设置 2:MANAGED几乎不做任何事情,既不会提交也不会回滚事物,而是交给容器来管理事物声明周期 --> <transactionManager type="JDBC"></transactionManager> <!-- 1:UNPOOLED这个数据源的实现是每次被请求时简单打开和关闭连接。 2:POOLED这是JDBC连接对象的数据源连接池的实现,用来避免创建新的连接实例 3:JNDI这个数据源的实现是为了使用如Spring或应用服务器这类的容器,容器可以集中或在外部配置数据源,然后放置一个JNDI上下文的引用。 这个数据源配置只需要两个属性:initial_context data_source --> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <proxyFactory type=""></proxyFactory> <!-- <settings> <setting name="LazyLoadingEnable" value="false"/> </settings> --> <!-- 定义别名,可以使用别名,而不用在每次使用时都指定完整的包名 --> <typeAliases> <typeAlias alias="GameServerMapper" type="org.mybatis.mapper.GameServerMapper"/> </typeAliases> <!-- 指定类型转换器,需要实现TypeHandler接口 --> <!-- <typeHandlers> <typeHandler handler="org.apache.ibatis.type.TypeHandler.DateHandler" javaType="java.util.Date" jdbcType="Date"/> </typeHandlers> --> <!-- 每次创建实例使用的方法:继承DefaultObjectFactory --> <!-- <objectFactory type="org.apache.ibatis.type.factory.MyObjectFactory"></objectFactory> --> <!-- 在某一点拦截已经映射语句的调用。实现Interceptor接口,通过注解指定需要拦截的操作等信息 --> <!-- <plugins> <plugin interceptor="org.apache.ibatis.type.plugin.InsertPlugin"></plugin> </plugins> --> <!-- 告诉Mybatis,到哪里寻找映射文件 --> <mappers> <mapper resource="org/mybatis/mapper/PlayerMapper.xml" /> </mappers> </configuration>