5 - TypeHandler-1

当需要将jdbc类型的数据和Java程序中类型的书数据进行转换时,可以使用TypeHandler来完成转换过程。怎么实现呢?
Java类型==》jdbc
将Java类型值value1通过某种策略转化为数据库(jdbc)类型值value2,然后将value2设置为SQL参数 :preparedStatement.setType(i,value2);
Java类型《== jdbc
resultSet中取出值value2,然后通过某种策略将value2转换为Java类型值value1

table

create table `student`(
`id` int auto_increment primary key,
`name` varchar(30) not null,
`age` int,
`birthday` varchar(30)
)auto_increment=10000;

model

package model;

import java.util.Date;

public class Student {
    private int id;
    private String name;
    private int age;

    private Date birthday;//在数据库中对应的类型是varchar(n)

    public Student() {
    }
//getter和setter略
}

TypeHandler


//表注转换的两种类型
@MappedJdbcTypes({JdbcType.VARCHAR})//jdbc类型
@MappedTypes({java.util.Date.class})//程序类型
public class MyDateTypeHandler extends BaseTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {

        preparedStatement.setString(i,String.valueOf(date.getTime()));
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return new Date(resultSet.getLong(i));
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return new Date(resultSet.getLong(s));
    }

    @Override
    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return new Date(callableStatement.getLong(i));
    }
}

dao

package dao;

import model.Student;

public interface StudentMapper {

    int insertStudent(Student student);

    Student selectStudentById(int id);
}

mapper

在对应参数处使用typeHandler来转换
作为输入参数:
#{birthday,typeHandler=dao.MyDateTypeHandler}
这里的typeHandler的值不成写成字符串类型
作为输出结果:

 
        insert into `student`(`name`,`age`,`birthday`)
        values(#{name},#{age},#{birthday,typeHandler=dao.MyDateTypeHandler})
        
            select last_insert_id()
        
    

    
        
        
        
        
    

    

test


public class AppTest {

    SqlSessionFactory factory = null;

    @Before
    public void prepare() throws IOException{
        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        factory = new SqlSessionFactoryBuilder().build(inputStream);
        inputStream.close();
    }

    @Test
    public void test(){
        SqlSession session = factory.openSession();
        try{
            StudentMapper studentMapper = session.getMapper(StudentMapper.class);
//            Student student = new Student("wang",20,new Date());
//            int affectedRows = studentMapper.insertStudent(student);
            int id=10001;
            Student student  = studentMapper.selectStudentById(id);

            System.out.println(student);
        }finally{
            session.commit();
            session.close();
        }
    }
}

你可能感兴趣的:(5 - TypeHandler-1)