1. Mybatis入門,基於xml配置和完全基於代碼的使用

在程序處理過程中我們一般都需要和數據庫進行交互,從數據庫獲取結果之後需要將相應的結果轉換爲程序對應實體對象,基於JDBC底層的需要我們進行手動的設置,比較繁瑣,爲此誕生了例如:hibernate。Mybatis等orm框架(Object Relational Mapping,對象關係映射模型)。
一般我們在程序中如果需要使用mybatis一般需要進行如下配置:

  1. 首先是pom配置:
 	<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>
  1. 基於xml配置mybatis-config.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>
    <properties resource="jdbc.properties"/>
    <typeAliases>
        <typeAlias type="com.leo.test.mybatis.entity.Person" alias="person"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>
    <mappers>
        <mapper resource="com/leo/test/mybatis/mapper/PersonMapper.xml"/>
       <!--或者使用
        <package name="com.leo.test.mybatis.mapper"/> -->
    </mappers>
</configuration>
  1. 編寫mapper配置文件和mapper接口:
<!--- PersonMapper.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="com.leo.test.mybatis.mapper.PersonMapper">
    <select id="selectPerson" resultType="person">
        select * from person where id = #{id}
    </select>
</mapper>
public interface PersonMapper {
    public Person selectPerson(int id);
}
  1. 啓動類:
public class Bootstrap {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        String config = "mybatis-config.xml";
        try (InputStream inputStream = Resources.getResourceAsStream(config)) {
            sqlSessionFactory =
                    new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        SqlSession sqlSession = null;
        try{
            sqlSession = getSqlSession();
            PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
            Person person = personMapper.selectPerson(1);
            System.out.println(person.getName());
        }finally {
            close(sqlSession);
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
    public static void close(SqlSession sqlSession){
        if(sqlSession != null){
            try{
                sqlSession.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

完全基於代碼的處理如下:

// PersonMapperByAnnotation.java
public interface PersonMapperByAnnotation {
    @Select(value = "select * from person where id = #{id}")
    public Person selectPerson(int id);
}

// Bootstrap .java
public class Bootstrap {
    public static void main(String[] args) {
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://10.201.83.207:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("test",transactionFactory,dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.getTypeAliasRegistry().registerAlias("person", Person.class);
        configuration.addMapper(PersonMapperByAnnotation.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PersonMapperByAnnotation mapper = sqlSession.getMapper(PersonMapperByAnnotation.class);
        Person p = mapper.selectPerson(1);
        System.out.println(p.getName());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章