- dao(mapper)层CRUD的注解替代了Mapper.xml文件
查询 :@Select
添加 :@Insert
修改 :@Update
删除 :@Deletepackage com.itheima.dao; import com.itheima.domain.Book; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface BookDao { @Select("select * from tbl_book") List<Book> selectAll(); @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})") boolean addBook(Book book); @Delete("delete from tbl_book where id = #{id}") boolean deleteById(Integer id); @Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id=#{id}") boolean updateById(Book book); @Select("select * from tbl_book where id=#{id}") Book selectById(Integer id); }
- 在com.QT.config层下设置JdbcConfig类,MybatisConfig类来替代Mybatis-config.xml文件
package com.itheima.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; @PropertySource("classpath:jdbc.properties") public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource getDataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } //开启事务对象 @Bean public PlatformTransactionManager getPlatformTransactionManager(DataSource dataSource){ DataSourceTransactionManager manager = new DataSourceTransactionManager(); manager.setDataSource(dataSource); return manager; } }
package com.itheima.config; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; public class MybatisConfig { @Bean public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //给实体类起别名 bean.setTypeAliasesPackage("com.itheima.domain"); return bean; } @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer configurer = new MapperScannerConfigurer(); //扫描指定的层 configurer.setBasePackage("com.itheima.dao"); return configurer; } }
- 若要在方法或者类开启事务只需要在其上方加入注解@
Transactional
并且需要在springConfig上加注解@EnableTransactionManagement