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);

}
Spring数据库编程和MyBatis框架是两种不同的数据库访问方式,它们有以下区别: 1. 设计理念: - Spring数据库编程是基于Spring框架的一种数据库访问方式,它提供了一套统一的API和一系列的模板类,用于简化数据库操作。Spring数据库编程注重于整合各种数据访问技术,提供了更高层次的抽象和更强大的功能。 - MyBatis框架是一种轻量级的持久层框架,它通过XML或注解的方式将SQL语句与Java代码进行映射,提供了灵活的SQL编写和结果映射功能。 2. 配置方式: - Spring数据库编程需要在Spring配置文件中配置数据源、事务管理器等相关信息,并使用Spring提供的JdbcTemplate等模板类进行数据库操作。 - MyBatis框架需要配置MyBatis的核心配置文件,其中包括数据库连接信息、映射文件路径等,同时还需要编写SQL映射文件或使用注解进行SQL语句与Java代码的映射。 3. SQL编写方式: - Spring数据库编程使用JdbcTemplate等模板类提供的方法进行SQL操作,可以直接在Java代码中编写SQL语句。 - MyBatis框架将SQL语句与Java代码进行分离,可以通过XML文件或注解的方式编写SQL语句,提供了更灵活的SQL编写方式。 4. 对象关系映射: - Spring数据库编程可以使用Spring提供的ORM框架(如Hibernate)进行对象关系映射 - MyBatis框架本身不提供对象关系映射功能,但可以与其他ORM框架(如Hibernate)结合使用。 5. 社区支持和生态系统: - Spring是一个非常庞大且活跃的开源框架,有着广泛的社区支持和完善的生态系统。 - MyBatis也有一定的社区支持,但相对于Spring来说规模较小。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值