推广

java基础-day51-Spring01

iseeyu3年前 (2024-02-22)推广125

image.png

一、xml方式访问数据库


1.1 Spring的JdbcTemplate

Spring的JdbcTemplate(了解会用)
在Spring中提供了一个可以操作数据库的对象org.springframework.jdbc.core.JdbcTemplate,对象封装了jdbc技术,JDBC的模板对象与DBUtils中的QueryRunner非常相似.

测试:
在pom.xml中导入依赖

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-jdbc</artifactId>
     <version>5.0.2.RELEASE</version>
 </dependency>

编写测试类:

JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);

List<User> list = jt.query("select * from user where id =?",new BeanPropertyRowMapper<User>(User.class),1);

System.out.println(list.get(0));

//jt.update("delete from  user where id =?",4);

1.2 创建user表并添加数据

CREATE TABLE USER(

id INT,
username VARCHAR(20),
PASSWORD VARCHAR(20)

)

1.3 pom.xml导入相关依赖

<dependencies>
     <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <version>1.18.12</version>
     </dependency>

     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>5.2.6.RELEASE</version>
     </dependency>

     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>5.2.6.RELEASE</version>
     </dependency>

     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>8.0.20</version>
     </dependency>

     <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>druid</artifactId>
         <version>1.1.19</version>
     </dependency>
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
         <scope>test</scope>
     </dependency>

 </dependencies>

1.3 编写pojo

package com.qf.pojo;

import lombok.Data;

@Data
public class User {

 private Integer id;
 private String name;
 private String password;

}

1.4 编写dao

package com.qf.dao;

import com.qf.pojo.User;

import java.util.List;

public interface UserDao {

 List<User> findAll();
}

package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

 private JdbcTemplate jdbcTemplate;

 public List<User> findAll() {

     return  jdbcTemplate.query("select * from user",new BeanPropertyRowMapper<User>(User.class));

 }

 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
     this.jdbcTemplate = jdbcTemplate;
 }
}

1.5 编写service

package com.qf.service;

import com.qf.pojo.User;

import java.util.List;

public interface UserService {

 List<User> findAll();
}

package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

public class UserServiceImpl implements UserService {

 private UserDao userDao;

 public List<User> findAll() {
     return userDao.findAll();
 }

 public void setUserDao(UserDao userDao) {
     this.userDao = userDao;
 }
}

1.6 编写controller

package com.qf.cotroller;

import com.qf.pojo.User;
import com.qf.service.UserService;

import java.util.List;

public class UserController {

 private UserService userService;

 public List<User> findAll(){

     return userService.findAll();
 }

 public void setUserService(UserService userService) {
     this.userService = userService;
 }
}

1.7 jdbc.properties配置文件

jdbc.username = root
jdbc.password= root
jdbc.url = jdbc:mysql:///java2001?serverTimezone=Asia/Shanghai
jdbc.driverClassName = com.mysql.cj.jdbc.Driver

1.8 applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

     <!-- 引入jdbc.properties配置文件 -->
     <context:property-placeholder location="classpath:jdbc.properties"/>

     <!-- 配置druid数据库连接池 -->
     <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
             <property name="username" value="${jdbc.username}"></property>
             <property name="password" value="${jdbc.password}"></property>
             <property name="url" value="${jdbc.url}"></property>
             <property name="driverClassName" value="${jdbc.driverClassName}"></property>

     <!-- 配置spring的jdbcTemplate-->
     <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
             <property name="dataSource" ref="dataSource"></property>
     </bean>

     <!-- dao -->
     <bean name="userDao" class="com.qf.dao.impl.UserDaoImpl">
             <property name="jdbcTemplate" ref="jdbcTemplate"></property>
     </bean>

     <!-- service -->
     <bean name="userService" class="com.qf.service.impl.UserServiceImpl">
             <property name="userDao" ref="userDao"></property>
     </bean>

     <!-- controller -->
     <bean name="userController" class="com.qf.cotroller.UserController">
             <property name="userService" ref="userService"></property>
     </bean>

</beans>

1.9 测试

package com.qf.test;

import com.alibaba.druid.pool.vendor.SybaseExceptionSorter;
import com.qf.cotroller.UserController;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestUserController {

 @Test
 public void test_findAll(){

     ClassPathXmlApplicationContext applicationContext =
             new ClassPathXmlApplicationContext("applicationContext.xml");

     UserController userController =
             (UserController)applicationContext.getBean("userController");

     List<User> list = userController.findAll();

     System.out.println(list);
 }
}

二、注解方式访问数据库


2.1 Spring中的注解

@Configuration
作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

@ComponentScan
作用:用于通过注解指定spring在创建容器时要扫描的包
属性:value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
等同于xml中: <context:component-scan base-package=”com.qf”/>

@PropertySource
作用:用于指定properties文件的位置
属性:value:指定文件的名称和路径。
关键字:classpath,表示类路径下

等同于xml中: <context:property-placeholder location=”classpath:jdbc.properties”/>

@Bean
作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性:name:用于指定bean的id。当不写时,默认值是当前方法的名称
细节:当我们使用注解配置方法时,如果方法有参数,在参数前加:@Qualifier(“@Bean注解中name的值”),spring框架会去容器中查找有没有可用的bean对象查找的方式和Autowired注解的作用是一样的。

 @Bean("dataSource1")
 public DataSource getDataSource1(){
  try{
      Properties pro = new Properties();
      pro.setProperty("url",url);
      pro.setProperty("username",username);
      pro.setProperty("password",password);
      pro.setProperty("driverClassName",driver);

      DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);
      return dataSource;

  } catch (Exception e){
  }
     return null;
 }

 @Bean("dataSource2")
 public DataSource getDataSource2(){
     try{
         Properties pro = new Properties();
         pro.setProperty("url",url);
         pro.setProperty("username",username);
         pro.setProperty("password",password);
         pro.setProperty("driverClassName",driver);

         DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);
         return dataSource;

     } catch (Exception e){
     }
     return null;
 }

 @Bean("dataSource")
 public DataSource getDataSource(@Qualifier("dataSource1") DataSource ds){
     return ds;
 }

@Import
作用:用于导入其他的配置类
属性:value:用于指定其他配置类的字节码。
当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类

等同于xml中:  <import resource="xxx.xml"></import>

2.2 创建pojo,dao,service,controller

使用@Repository,@Service,@Controller以及@Autowired 配置所需代码

2.3 创建jdbc.properties配置文件

jdbc.username = root
jdbc.password= root
jdbc.url = jdbc:mysql:///java2001?serverTimezone=Asia/Shanghai
jdbc.driverClassName = com.mysql.cj.jdbc.Driver

2.5 创建SpringConfiguration.java作为注解配置类,它的作用和bean.xml是一样的

package com.qf.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Properties;


@PropertySource(value = "classpath:jdbc.properties")
@ComponentScan("com.qf")
@Configuration
public class SpringConfiguration {

 @Value("${jdbc.driverClassName}")
 private String driverClassName;

 @Value("${jdbc.url}")
 private String url;

 @Value("${jdbc.username}")
 private String username;

 @Value("${jdbc.password}")
 private String password;

 @Bean("jdbcTemplate")
 public JdbcTemplate getJdbcTemplate(){

     try{
         Properties pro = new Properties();
         pro.setProperty("url",url);
         pro.setProperty("username",username);
         pro.setProperty("password",password);
         pro.setProperty("driverClassName",driverClassName);

         DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);

         JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
         return jdbcTemplate;

     } catch (Exception e){

     }
     return null;
 }
}

2.6 使用Spring整合junit测试

Spring整合junit的配置
1. 导入spring整合junit坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
2. 使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
@RunWith(SpringJUnit4ClassRunner.class)

  1. 告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
    @ContextConfiguration(locations = “classpath:applicationContext.xml”)
    locations:指定xml文件的位置,classpath关键字表示在类路径下

    @ContextConfiguration(classes = SpringConfiguration.class)
    classes:指定注解配置类(需要手动编写配置类)

注意:当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上,spring版本必须保持一致

2.7 编写测试类进行测试

package com.qf.test;

import com.qf.config.SpringConfiguration;
import com.qf.cotroller.UserController;
import com.qf.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class TestUserController {

 @Autowired
 private UserController userController;

 @Test
 public void test_findAll() throws Exception{

     List<User> list = userController.findAll();

     System.out.println(list);

 }

}

扫描二维码推送至手机访问。

版权声明:本文由西安泽虎代运营发布,如需转载请注明出处。

转载请注明出处https://www.0291.com.cn/post/56347.html

相关文章

西安企业做百度推广,一个月花三千和花三万到底差在哪?

4|最近跟几个西安的老板聊天,发现一个挺有意思的现象:同样做百度推广,有人一个月花三千块,询盘不断;有人一个月砸三万,水花都没见着。问他们区别在哪,大多数人说不清楚,只知道'钱花了,没效果'。 5| 6|百度推广这东西,说复杂也复杂,说简单也简单。核心就一件事:让你的潜在客户搜某个词的时候,你的信息...

我想当策划,大学应该选什么专业?

我想当策划,大学应该选什么专业?

学,广告,传播,公关,这些专业其实都可以。另外也可以学像汉语言文学,以及一些跟文学相关的一些专业,会对你找工作有帮助。但是,你想从事这个这份职业,除了专业的学习之外,更多的是,你要在上学的时候积极参与一些更营销策划相关的社会实践。比如说你可以做一些兼职,比如说帮别人去写稿,...

服装市场营销策略分析,“定位不慎满盘皆输”

服装市场营销策略分析,“定位不慎满盘皆输”

不同的区域需要不同的策略,而不同的营销策略需要不同的销售思路来配合。因此,在研究女装产品销售思路之前,最好先对于市场与营销策略做一次深入地了解。1.市场区域化(market segmentation):目标营销的第一步,是将整个市场拆分成若干个同性质的小市场。2.目标市场的...

晚间悦读丨你的思维方式,决定你的人生高度!

晚间悦读丨你的思维方式,决定你的人生高度!

越长大,越发现,能够决定你人生高度的,往往是你的认知层次。 你的认知在哪个层级,你的人生就处在什么状态。你认知的高度,决定了你人生的高度。 那如何才能升级方式、提升认知能力呢?可以从这三个方面做出改变。 NO. 1 改变态度 有人...

编写项目营销策划方案六大要点

编写项目营销策划方案六大要点

现在商业发展非常迅速,的需求非常的大,但是要做好营销策划是有一定难度的,我把自己做营销策划的一些体会在这里分享给朋友们。营销策划方案六大要点我们先说项目营销策划方案这个话题。大部分的营销策划人都是在企业里工作,大部分项目之初都是来源于一个想法,创始人、老板或者创始团队的一个...

【商场营销策划】如何进行商场营销策划?

【商场营销策划】如何进行商场营销策划?

商场是策划者们关注的永恒话题,那么究竟该如何作好商场营销策划呢?掌握以下这几点营销策略设计原则,至关重要!1.义利兼顾的原则。商场在获取利润的同时要充分考虑到消费者的合法利益和商场的长远利益。在作商场活动营销策略方案的时候应该将这一点作为首要的原则。对商场有利而对顾客不利的...

现在,非常期待与您的又一次邂逅

我们努力让每一部企业宣传片和抖音短视频成为商业大片