Spring数据库编程

  • 传统的JDBC操作数据库,性能最好但是代码重复并且存在大量的try…catch…finally语句。
<!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="maxActive" value="${jdbc.maxActive}"/>
    <property name="maxIdle" value="${jdbc.maxIdle}"/>
    <property name="maxWait" value="${jdbc.maxWait}"/>
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--使用JdbcTemplate操作数据库-->
public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
    JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class);
    Long id = 1L;
    String sql = "select id, lecture_name, note from t_lecture where id = " + id;
    Lecture lecture = jdbcTemplate.queryForObject(sql, new RowMapper<Lecture>() {
        @Override
        public Lecture mapRow(ResultSet rs, int rowNum) throws SQLException {
            Lecture result = new Lecture();
            result.setId(rs.getLong("id"));
            result.setLectureName(rs.getString("lecture_name"));
            result.setNote(rs.getString("note"));
            return result;
        }
    });
    System.out.println(lecture);
}
  • JdbcTemplate好处:无需书写关闭数据库连接的代码,JdbcTemplate在内部实现了它们。但是,JdbcTemplate不支持事务,需要引入对应的事务管理器。
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="mybatis-config.xml"/>
</bean>
<!--MyBatis配置文件-->
<configuration>

    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="defaultStatementTimeout" value="3000"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="useGeneratedKeys" value="true"/>
        <setting name="defaultExecutorType" value="REUSE"/>
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

    <typeAliases>
        <typeAlias type="com.spring.data.Lecture" alias="lecture"/>
    </typeAliases>

    <mappers>
        <mapper resource="mapper/LectureMapper.xml"/>
    </mappers>

</configuration>
<!--Mapper.xml文件,书写SQL语句-->
<mapper namespace="com.spring.data.LectureMapper">

    <insert id="insertLecture" parameterType="lecture" useGeneratedKeys="true" keyProperty="id">
        insert into t_lecture (lecture_name, note) values (#{lectureName}, #{note});
    </insert>

</mapper>
<!--测试MyBatis-->
public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
    LectureMapper lectureMapper = ctx.getBean(LectureMapper.class);
    Lecture lecture = new Lecture();
    lecture.setLectureName("JavaScript");
    lecture.setNote("xixi");
    lectureMapper.insertLecture(lecture);
    System.out.println(lecture.getId());
}
  • 使用SqlSessionTemplate组件,它是一个线程安全的类,确保了每个线程的SqlSession唯一且互相不冲突,还提供了一些增删改查的功能。
<!--声明SqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="sqlSessionFactory"/>
    <constructor-arg value="BATCH"/>
</bean>
<!--测试SqlSessionTemplatee-->
public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
    SqlSessionTemplate sqlSessionTemplate = ctx.getBean(SqlSessionTemplate.class);
    Lecture lecture = new Lecture();
    lecture.setLectureName("HTML");
    lecture.setNote("haha");
    sqlSessionTemplate.insert("com.spring.data.LectureMapper.insertLecture", lecture);
    System.out.println(lecture.getId());
}
  • 使用MapperScannerConfigurer可以自动扫描,注册Mapper
<!--配置自动生成Mapper的代理类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--扫描的基础包-->
    <property name="basePackage" value="com.spring.data"/>
    <!--如果同时配置了SqlSessionTemplate,则使用SqlSessionTemplate-->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!--被此注解表示的类才会进行扫描-->
    <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
    <!--也可以使用标记接口的方式,只要实现此接口的类都会被扫描,注册为Mapper-->
    <property name="markerInterface" value="com.spring.data.BasicMapper"/>
</bean>
@Repository
public interface LectureMapper {

    int insertLecture(Lecture lecture);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值