Java-iBATIS

1、是什么?

2010年迁移到了google code,并且改名为MyBatis。ibatis1、ibatis2、到了版本3就改名为mybatis。
iBATIS的是一个持久层框架,它能够自动在 Java, .NET, 和Ruby on Rails中与SQL数据库和对象之间的映射。映射是从应用程序逻辑封装在XML配置文件中的SQL语句脱钩。
iBATIS是一个轻量级的框架和持久性API适合持久化的POJO(普通Java对象)。
iBATIS是被称为一个数据映射和映射需要的类的属性和数据库中的表的列之间的参数和结果。
iBATIS和其他持久化框架,如Hibernate之间的显著区别在于,iBATIS强调使用SQL,而其他的框架通常使用一个自定义的查询语言。
iBatis设计理念:简单,快速开发,可移植性,Java,Ruby和C#,微软.NET实现,独立的接口,开源。
IBATIS的优点
  支持存储过程:iBATIS的SQL封装以存储过程的形式,使业务逻辑保持在数据库之外,应用程序更易于部署和测试,更便于移植。
  支持内嵌的SQL:预编译器不是必需的,并有完全访问所有的SQL语句的特性。
  支持动态SQL: iBATIS特性提供基于参数动态生成SQL查询。
  支持O / RM:iBATIS支持许多想通的功能,作为一个O / RM工具,如延迟加载,连接抓取,缓存,运行时代码生成和继承。

2、iBATIS配置

a)下载并导入 ibatis的jar包:
  ibatis2-sqlmap-2.1.7.597.jar,
  ibatis2-common-2.1.7.597.jar;
b)添加ibatis的配置文件iBatisConfig.xml。文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings useStatementNamespaces="true"/>
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" 
value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="JDBC.ConnectionURL"
value="jdbc:sqlserver://localhost:1433; DatabaseName=OtherDb"/>
<property name="JDBC.Username" value="sa"/>
<property name="JDBC.Password" value="dacude2017"/>
</dataSource>
</transactionManager> 
<!-- 实体类的映射文件路径 -->
<sqlMap resource="dao/Person.xml"/>
</sqlMapConfig>

c)这里使用的数据库是sql server2008,所以下载并导入对应的JDBC包

  mssql-jdbc-6.2.1.jre8;

3、编写ibatis的访问类

package iBatisTest;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.common.resources.Resources;

import java.io.Reader;

public class IbatisSqlMapClient {
    private static final SqlMapClient sqlMap;
    static {
        try {
            String resource = "config/iBatisConfig.xml";//你的配置文件路径
            Reader reader = Resources.getResourceAsReader(resource);
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error initializing IbatisSqlMap class.Cause;" + e);
        }
    }
    public static SqlMapClient instance() {
        return sqlMap;
    }
}

4、实体类的映射文件

数据库建立表Person,编写实体类Person,编写实体类的映射文件(Map 文件)Person.xml;person.xml实例内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
        PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
        "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap>
<!-- 通过typeAlias使得我们在下面使用实体类的时候不需要写包名 -->
    <typeAlias alias="Person" type="iBatisTest.Person"/>
<!--restultMap主要是用于Ibatis对数据增删改查操作的返回值结果对于java对象的映射
    ,一般用于所返回的对象可能包含的是一个以上java对象的字段,
    如果是一个java对象中的字段一般使用resultClass--> 
    <resultMap id="personMap" class="Person">
<!--result property=”java实体类中的属性名” column=”数据库表中的列名”--> 
        <result property="personName" column="PersonName"></result>
        <result property="personId" column="personId"></result>
        <result property="personAge" column="personAge"></result>
        <result property="personEmail" column="personEmail"></result>
    </resultMap>
    
    <insert id="insertPerson" parameterClass="Person">
        INSERT INTO Person
        ( PersonName, PersonAge, PersonEmail)
        Values
        (#personName#,#personAge#,#personEmail#)
        <!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: -->
<!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->
<!-- mssql:select @@IDENTITY as value -->
<!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->
<!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。
有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->
        <selectKey resultClass="int" keyProperty="personId">
            select @@identity as personId        
        </selectKey>
    </insert>
    <update id="updatePerson" parameterClass="Person">
        UPDATE Person SET
        PersonName=#personName#,PersonAge=#personAge#,PersonEmail=#personEmail#
        WHERE PersonId=#personId#
    </update>
    <delete id="deletePerson" parameterClass="int">
        DELETE Person WHERE PersonId=#personId#
    </delete>
    <select id="getPersonById" parameterClass="int" resultClass="Person">
        SELECT
        PersonId,PersonName,PersonAge,PersonEmail
        FROM Person
        WHERE PersonId=#personId#
    </select>
    <select id="allPersonList" resultMap="personMap">
        SELECT
        PersonId,PersonName,PersonAge,PersonEmail
        FROM Person
    </select>
</sqlMap>
Person.xml

5、编写DAO层实现PersonDaoImpl

package iBatisTest;

import java.sql.SQLException;
import java.util.List;

public class PersonDaoImpl  implements PersonDao {
    public void insertPerson(Person person) throws SQLException {
        int id=(int)IbatisSqlMapClient.instance().insert("insertPerson", person);
        System.out.println("newId:"+id);
    }

    public void updatePerson(Person person) throws SQLException {
        IbatisSqlMapClient.instance().update("updatePerson", person);
    }

    public Person getPersonById(int personId) throws SQLException {
        return (Person) IbatisSqlMapClient.instance().queryForObject("getPersonById", personId);
    }

    public void deletePerson(int personId) throws SQLException {
        IbatisSqlMapClient.instance().delete("deletePerson", personId);
    }

    public List allPersonList() throws SQLException {
        return IbatisSqlMapClient.instance().queryForList("allPersonList", null);
    }
}

 

 

6、测试(略)。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

补充说明:

2.1 JDBC全称:Java Data Base Connectivity(java数据库连接)。JDBC仅仅是一个接口,通过JDBC去加载对应的驱动程序,进而来操作数据库。换句话说,JDBC需要依赖对应数据库的驱动程序才可以访问数据库。 就是开发JDBC应用时除了需要以上2个包的支持外,还需要导入相应JDBC的数据库实现(即数据库驱动)。
  组成JDBC的2个包:Java.sql和javax.sql(必须)
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
4.1 selectKey 使用时,需要保证keyProperty的值是类的属性或者数据库的字段, 我使用id,保存,找不到它。
  <selectKey resultClass="int" keyProperty="personId">
    select @@identity as personId
  </selectKey>
4.2如果xml 中没有ibatis 的提示,则window --> Preference--> XML-->XML Catalog---> 点击add
  选择uri URI: 请选择本地文件系统上 iBatisDemo1/WebContent/WEB-INF/lib/sql-map-config-2.dtd 文件;
    Key Type: 选择Schema Location;
    Key: 需要联网的,不建议使用;
4.3 Ibatis的SQL Map:
  (1).Ibatis的SQL Map的核心概念是Mapped Statement。Mapped Statement可以使用任意的SQL语句,并拥有 parameterMap/parameterClass(输入参数)和resultMap/resultClass(输出结果)。
  (2). <statement>元素是个通用的声明,可以用于任何类型的SQL语句,但是通常使用具体的<statement>类型, 如:查询使用<select>,添加使用<insert>,更新使用<update>,删除使 用<delete>。
4.4 实体类必须遵循JavaBean的规范,提供一个无参数的构造方法,字段必须提供get和set方法。因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题。

转载于:https://www.cnblogs.com/dacude/p/7409783.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
// JBuilder API Decompiler stub source generated from class file // 2010-1-15 // -- implementation of methods is not available package com.ibatis.common.jdbc; // Imports import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Savepoint; import java.sql.Statement; import java.util.Map; public class SimplePooledConnection implements InvocationHandler { // Fields private static final String CLOSE = "close"; private static final Class[] IFACES; private int hashCode; private SimpleDataSource dataSource; private Connection realConnection; private Connection proxyConnection; private long checkoutTimestamp; private long createdTimestamp; private long lastUsedTimestamp; private int connectionTypeCode; private boolean valid; // Constructors public SimplePooledConnection(Connection connection, SimpleDataSource dataSource) { } // Methods public void invalidate() { } public boolean isValid() { return false;} public Connection getRealConnection() { return null;} public Connection getProxyConnection() { return null;} public int getRealHashCode() { return 0;} public int getConnectionTypeCode() { return 0;} public void setConnectionTypeCode(int connectionTypeCode) { } public long getCreatedTimestamp() { return 0L;} public void setCreatedTimestamp(long createdTimestamp) { } public long getLastUsedTimestamp() { return 0L;} public void setLastUsedTimestamp(long lastUsedTimestamp) { } public long getTimeElapsedSinceLastUse() { return 0L;} public long getAge() { return 0L;} public long getCheckoutTimestamp() { return 0L;} public void setCheckoutTimestamp(long timestamp) { } public long getCheckoutTime() { return 0L;} private Connection getValidConnection() { return null;} public int hashCode() { return 0;} public boolean equals(Object obj) { return false;} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null;} public Statement createStatement() throws SQLException { return null;} public PreparedStatement prepareStatement(String sql) throws SQLException { return null;} public CallableStatement prepareCall(String sql) throws SQLException { return null;} public String nativeSQL(String sql) throws SQLException { return null;} public void setAutoCommit(boolean autoCommit) throws SQLException { } public boolean getAutoCommit() throws SQLException { return false;} public void commit() throws SQLException { } public void rollback() throws SQLException { } public void close() throws SQLException { } public boolean isClosed() throws SQLException { return false;} public DatabaseMetaData getMetaData() throws SQLException { return null;} public void setReadOnly(boolean readOnly) throws SQLException { } public boolean isReadOnly() throws SQLException { return false;} public void setCatalog(String catalog) throws SQLException { } public String getCatalog() throws SQLException { return null;} public void setTransactionIsolation(int level) throws SQLException { } public int getTransactionIsolation() throws SQLException { return 0;} public SQLWarning getWarnings() throws SQLException { return null;} public void clearWarnings() throws SQLException { } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null;} public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null;} public Map getTypeMap() throws SQLException { return null;} public void setTypeMap(Map map) throws SQLException { } public void setHoldability(int holdability) throws SQLException { } public int getHoldability() throws SQLException { return 0;} public Savepoint setSavepoint() throws SQLException { return null;} public Savepoint setSavepoint(String name) throws SQLException { return null;} public void rollback(Savepoint savepoint) throws SQLException { } public void releaseSavepoint(Savepoint savepoint) throws SQLException { } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null;} public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return null;} }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值