码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis(二)

时间:2017-05-21 19:44:40      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:append   .class   public   factor   映射   文件内容   磁盘   引入   cep   

1 Mybatis映射文件--增删改查

  • POJO类
package cn.demo1;

import org.apache.ibatis.type.Alias;

/**
 * 描述:POJO
 */
@Alias("emp")
public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName=‘" + lastName + ‘\‘‘ +
                ", gender=‘" + gender + ‘\‘‘ +
                ", email=‘" + email + ‘\‘‘ +
                ‘}‘;
    }
}
  • EmployeeMapper.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="cn.demo1.IEmployeeDAO">
<!--
    namespace:命名空间  指定为接口的全类名
    id:唯一标识 和接口中的方法名相同
    resultType:返回值类型
-->
<select id="findById" parameterType="int" resultType="emp" databaseId="mysql">
    select id,last_name,email,gender from employee where id = #{id}
</select>

<insert id="addEmployee" parameterType="cn.demo1.Employee">
    insert into employee(last_name,email,gender) values (#{lastName},#{email},#{gender})
</insert>

<update id="updateEmployee" parameterType="cn.demo1.Employee">
    update employee set last_name = #{lastName} ,email = #{email},gender = #{gender} where id = #{id}
</update>

<delete id="deleteEmployeeById" parameterType="java.lang.Integer">
    delete from employee where id = #{id}
</delete>

</mapper>
  • IEmployeeDAO
package cn.demo1;



public interface IEmployeeDAO {
    public Employee findById(Integer id);

    public void addEmployee(Employee employee);

    public void updateEmployee(Employee employee);

    public void deleteEmployeeById(Integer id);
}
  • 配置文件--log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ###

log4j.rootLogger=debug, stdout
  • 配置文件--db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.user=root
jdbc.password=root
  • 配置文件--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>

    <!--
        Mybatis可以使用properties属性来引入外部properties配置文件内容
            resource:引入类路径下的资源
            url:引入网络路径或磁盘路径下的资源
    -->
    <properties resource="db.properties"></properties>
    
    <settings>
        <!--
            是否开启自动驼峰规则映射,即如果数据表中的字段是last_name到Java中的lastName等类似的映射
         -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--
        typeAliases:别名处理器,可以为Java类型起别名
    -->
    <typeAliases>
        <!--
            类很多情况下,可以批量设置别名这个包下的每一个类创建一个默认的别名,就是简单类名小写。
        -->
       <package name="cn.demo1"/>
    </typeAliases>

    <!--
        environments ,Mybatis可以配置多种环境
            environment,配置一个具体的环境信息,必须有两个标签,ID表示当前环境的唯一标识
                transactionManager s事务管理器
                    type 事务管理器的类型
                        JDBC   this.typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
                        MANAGER  this.typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
                dataSource
                        JNDI    this.typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
                        POOLED  this.typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
                        UNPOOLED  this.typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
    -->
    <environments default="mysql_development">
        <environment id="mysql_development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
        <environment id="oracle_development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${oracle.driver}"/>
                <property name="url" value="${oracle.url}"/>
                <property name="username" value="${oracle.user}"/>
                <property name="password" value="${oracle.password}"/>
            </dataSource>
        </environment>
    </environments>

    <databaseIdProvider type="DB_VENDOR">
        <property name="MySQL" value="mysql"/>
        <property name="Oracle" value="oracle"/>
        <property name="SQL Server" value="sqlserver"/>
    </databaseIdProvider>

    <mappers>
        <mapper resource="cn/demo1/EmployeeMapper.xml"/>
    </mappers>
</configuration>
  • 测试类
package cn.test;

import cn.demo1.Employee;
import cn.demo1.IEmployeeDAO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 *
 * 描述:
 */

public class MybatisTest {
    /**
     * 测试查询
     * @throws IOException
     */
    @Test
    public  void demo1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();

        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = dao.findById(1);
        System.out.print(employee);

        session.close();
    }

    /**
     * 测试增加
     * @throws IOException
     */
    @Test
    public  void demo2() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();

        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = new Employee();
        employee.setLastName("呵呵");
        employee.setGender("女");
        employee.setEmail("aaa@aaa.com");
        dao.addEmployee(employee);

        session.commit();
        session.close();
    }

    /**
     * 测试修改
     * @throws IOException
     */
    @Test
    public  void demo3() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();

        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = new Employee();
        employee.setId(1);
        employee.setLastName("呵呵");
        employee.setGender("女");
        employee.setEmail("aaa@aaa.com");
        dao.updateEmployee(employee);

        session.commit();
        session.close();
    }

    /**
     * 测试修改
     * @throws IOException
     */
    @Test
    public  void demo4() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();

        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        dao.deleteEmployeeById(1);

        session.commit();
        session.close();
    }



}

 

Mybatis(二)

标签:append   .class   public   factor   映射   文件内容   磁盘   引入   cep   

原文地址:http://www.cnblogs.com/xuweiweiailixing/p/6885546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!