(4) Spring study notes (AOP and JdbcTemplate)

AOP operations (AspectJ annotations)

1. Create a class and define methods in the class

public class User {
    public void add(){
        System.out.println("add...");
    }
}

2. Create enhanced classes (write enhanced logic)

(1) In the enhanced class, create methods so that different methods represent different notification types

// 增强类
public class UserProxy {
    // 前置通知
    public void before(){
        System.out.println("before...");
    }
}

3. Configure the notification

(1) In the spring configuration file, enable annotation scanning

(2) Create User and UserProxy using annotations

(3) Add the annotation @Aspect above the enhanced class

// 增强类
@Component
@Aspect // 生成代理对象
public class UserProxy {
    // 前置通知
    public void before(){
        System.out.println("before...");
    }
}

(4) Enable generation of proxy objects in the spring configuration file

    <!--开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy/>

4. Configure different types of notifications

(1) In the enhanced class, add a notification type annotation on the notification method, and use the entry point expression configuration.

// 增强类
@Component
@Aspect // 生成代理对象
public class UserProxy {
    // 前置通知
    // Before注解作为前置通知
    @Before(value = "execution(* com.demo..aopanno.User.add(..))")
    public void before(){
        System.out.println("before...");
    }
}
 @AfterReturning(value = "execution(* com.demo.aopanno.User.add(..))")
    public void AfterReturning(){
        System.out.println("AfterReturning......");
    }

    @After(value = "execution(* com.demo.aopanno.User.add(..))")
    public void after(){
        System.out.println("after......");
    }

    @AfterThrowing(value = "execution(* com.demo.aopanno.User.add(..))")
    public void afterThrowing(){
        System.out.println("afterThrongwing......");
    }

    @Around(value = "execution(* com.demo.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("环绕之前");

        // 被增强的方法执行
        ProceedingJoinPoint.proceed();

        System.out.println("环绕之后");
    }

5. Public entry point extraction

    @Pointcut(value = "execution(* com.demo.aopanno.User.add(..))")
    public void pointdemo(){
        
    }

6. There are multiple enhancement classes to enhance a class and set priority

(1) Add the annotation @Order (number type value) on the enhanced class, the smaller the number, the higher the priority

AOP operations (AspectJ configuration files)

1. Create two classes, the enhanced class and the enhanced class, and create methods

2. Create two objects in the spring configuration file

3. Configure the entry point in the spring configuration file

7. Fully use annotation development

Create a configuration class without creating an xml configuration file

@Configuration
@ComponentScan(basePackages = {})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop{
  
}

JdbcTemplate (concept and preparation)

1. What is JdbcTemplate

(1) The Spring framework encapsulates JDBC and uses JdbcTemplate to facilitate database operations

2. Preparations

(1) Introduce related jar packages

Spring-jdbc-5.2.6.REALEASE.jar

Spring-orm-5.2.6.REALEASE.jar

Spring-tx-5.2.6.REALEASE.jar

(2) Configure the connection pool in the spring configuration file

    <!--数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://user_db"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>

(3) Configure the JdbcTemplate object and inject DataSource

    <!--JdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

(4) Create service class, create dao class, inject jdbcTemplate object into dao

Start build scan

    <!--组件扫描-->
    <context:component-scan base-package="com.demo"/>

service

@Service
public class Book {
    //注入dao
    @Autowired
    private BookDao bookDao;
}

dao

@Repository
public class BookDaoImpl implements BookDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

JdbcTemplate operates the database

1. Create an entity class corresponding to the database table

 

2. Write service and doa

(1) Perform database addition operation in dao

(2) Call the update method in the JdbcTemplate object to implement the add operation

  • has two parameters

  • The first parameter: sql statement

  • The second parameter: variable parameter, set the value of the sql statement

JdbcTemplate operates the database (modify and delete)

1. Modify

@Override
public void updateBook(Book book){
  String sql = "update t_book set username=?,ustatus=?where user id=?";
  Object[] args = {book.getUsername(),book.getUstatus(),book.getUserId()};
  int update = jdbcTemplate.update(sql,args);
  System.out.println(update);
}

2. delete

@Override
public void delete(String id){
  String sql = "delete from t_book where user id=?";
  int update = jdbcTemplate.update(sql, id);
  System.out.println(update);
  
}

3. Query (query returns a value)

(1) Query how much data is in the table, and use JdbcTemplate to realize the query and return a certain value code

@Override
public int selectCount(){
  String sql = "select count(*) from t_book";
  Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
  return count;
}

 

(2) Query return object

@Override
public Book findBookInfo(String id){
  String sql = "select * from t_book where user id=?";
  Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
  return book;
}

has three parameters

The first parameter: sql statement

The second parameter: RowMapper is an interface that returns different types of data. Use the implementation class in this interface to complete the data encapsulation.

The third parameter: sql statement value

(3) The query returns a collection

Summary: Use update() instead of adding and deleting, use queryForObject() to check a single return value, and use query() to check multiple return values

Batch operation:

1. Multiple records in the operation table

2. JdbcTemplate realizes batch adding operation

has two parameters

The first parameter: sql statement

The second parameter: List collection, add multiple record data

@Override
public void batchAddBook(List<Object[]> batchArgs){
  String sql = "insert into t_book values(?,?,?)";
  int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
  System.out.println(Arrays.toString(ints));
}
// 批量添加测试
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3", "java", "a"};
Object[] o2 = {"4", "c++", "b"};
Object[] o3 = {"5", "MySQL", "c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
// 调用批量添加
bookService.batchAdd(batchArgs);

 3. JdbcTemplate implements batch modification operations

@Override
public void batchUpdateBook(List<Object[]> batchArgs){
  String sql = "update t_book set username=?,ustatus=? where user_id=?";
  int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
  System.out.println(Arrays.toString(ints));
}

 4. JdbcTemplate realizes batch delete operation

@Override
public void batchDeleteBook(List<Object[]> batchArgs){
  String sql = "delete from t_book where user_id=?";
  int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
}

 

Guess you like

Origin blog.csdn.net/weixin_44516623/article/details/127902661