首页 > 数据库技术 > 详细

spring-dbutils&注解

时间:2020-09-22 22:41:19      阅读:60      评论:0      收藏:0      [点我收藏+]
dbutils使用和jdbctemplate大同小异:
ComboPooledDataSource dataSource = new ComboPooledDataSource(); //拿到连接池
//对数据源各种属性设置
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/db1");
dataSource.setUser("****");
dataSource.setPassword("****");
 
QueryRunner runner = new QueryRunner(dataSource);
//增删改用update
int count = runner.update("insert into account values(?,?,?)", null, "fbb", 1000f);
//查询用query,单个BeanHandler
Account account = runner.query("select * from account where id=?", new BeanHandler<Account>(Account.class), 1);
//查询多个BeanListHandler
List<Account> list = runner.query("select * from account", new BeanListHandler<Account>(Account.class));
 
注解
@Component(value = "accountService") 组件,用于标注普通类,也可标注特殊类,@Component("accountService"),不写id就是类名的首字母小写
@Controller  web->控制层->@Controller
@Service   业务逻辑->@Service
@Repository  Dao->数据仓库->@Repository
 
@Autowired
    作用:实现依赖注入(不依靠set方法、不依靠带参构造函数,原理是反射)
    装配(注入)方式:
        1.根据类型注入  byType
        2.根据类型注入如果存在多个对应类型,则根据名字注入  byName
@Qualifier(value = "accountDao")
    不能单独使用,主要作用是指定@Autowired注入的Bean对象,只找id,不看类型
@Resource
    作用:实现依赖注入
    装配方式:
        1.默认根据名字注入    byName
        2.如果名字注入找不到对应的Bean,则根据类型注入    byType
@Value
    作用:实现[基本数据类型和字符串]依赖注入
        主要用于将配置文件中的数据注入到JavaBean的属性中    jdbc.properties
        ${}:表示加载指定的配置文件中对应的key的值,如果不加${}则表示直接将值赋值给属性,${}是一个表达式使用
 
@Scope("singleton") //不写,默认singleton。prototype多例
 
@ComponentScan(basePackages = {"com.itheima.service","com.itheima.dao"})→@ComponentScan(value = {"com.itheima.service","com.itheima.dao"})→@ComponentScan({"com.itheima.service","com.itheima.dao"})
@Configuration //注解配置类,一般不用,用import在主配置文件中主动导入
@Import(JdbcConfig.class),引入另外一个配置类,把jq文件拖到我的代码里面
@Bean:将方法的返回值交给SpringIOC容器(ApplicationContext)对象管理
     Bean的ID默认为方法名字
     @Bean(name = "dataSource"),这里的name用于自定义Bean的ID
     如果该注解所在的方法有参数传入,则会从容器中注入进来
     注入方式:
         默认byType
         类型注入失败,则byName注入
 
@PropertySource("classpath:jdbc.properties")  //p源码注解
表示加载读取类路径下的jdbc.properties文件
 
 
SpringTest,可以在测试类中直接使用Spring注解
@RunWith注解    集成JUnit,创建Spring TestContextManager容器对象
@ContextConfiguration    指定配置文件或者配置类

spring-dbutils&注解

原文:https://www.cnblogs.com/21556guo/p/13714517.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!