Spring纯注解开发

本案例是对上一个案例的优化重在学会使用注解来实现Spring的增删改查,适用于刚入spring门的读者

先导pom依赖,【我的jdk是8 mysql也是8,其他版本不用关注】

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.nuo</groupId>
    <artifactId>day01spring</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!--spring核心依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.15</version>
        </dependency>

        <!--jdbcTemplate依赖所在-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <!--spring整合单元测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
    </dependencies>

</project>

创建表

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `birthday` date DEFAULT NULL,
  `sex` char(1) DEFAULT '男',
  `address` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3
-- 数据请自行导入【因为我找的以前的表插入数据语句找不到了。。】

applicationContext.xml就不需要了,直接删除

创建一个config包,里面放JavaConfig和JdbcConfig两个类

package com.nuo.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.ComponentScan;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

//纯注解开发,去Xml文件
//如果是bean标签就变成方法,方法名可用id名,class为返回值类型,并用@Bean注解.如果方法需要参数直接传入即可,spring会根据@AutoWire注入
//如果不是bean标签则变成新的注解

@ComponentScan("com.nuo")   /*相当于这个 <context:component-scan base-package="com.nuo"/>*/
public class JavaConfig {

	/*<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>*/
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        //创建
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //赋值
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

	/*<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql:///heima"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>*/

    /*不同的配置类还是分开好一点,把下面这些弄到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 DruidDataSource druidDataSource(){
        //创建
        DruidDataSource druidDataSource = new DruidDataSource();
        //赋值
        *//*为了后续方便弄个jdbc.properties引入
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql:///heima");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");*//*
        //弄成属性后直接传入
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }*/

}

为了后续方便在resource下面建个jdbc.properties引入,注意我是Mysql8,5这里不要cj

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/heima
jdbc.username=root
jdbc.password=root
package com.nuo.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.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration  //这个注解@Configuration代表此类是个配置类,会在容器启动时自动被加入到容器中,这样在别的配置类中就不用@Import来导入这个类了
@PropertySource("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 DruidDataSource druidDataSource(){
        //创建
        DruidDataSource druidDataSource = new DruidDataSource();
        //赋值
        /*为了后续方便弄个jdbc.properties引入
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql:///heima");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");*/
        //弄成属性后直接传入
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}

创建User实体类映射数据库表,这里我用的lomBok方便一点,idea2021以后不用再下载LomBok插件,直接在pom文件导入依赖即可

package com.nuo.pojo;

import lombok.*;
import java.sql.Date;


@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
       private Integer id;
       private String userName;
       private Date birthday;
       private String sex;
       private String address;
}

创建持久层接口

package com.nuo.dao;

import com.nuo.pojo.User;

import java.util.List;

public interface UserDao {
    //增
    void add(User user);

    //根据id删
    void deleteByid(Integer id);

    //根据id改
    void updateById(User user);

    //查所有
    List<User> getAll();

    //根据id查
    User getById(Integer id);
}

创建持久层实现类

package com.nuo.dao.impl;

import com.nuo.dao.UserDao;
import com.nuo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
//JdbcTemplate的update()方法:执行DML语句,执行增删改语句:
    @Override
    public void add(User user) {
        jdbcTemplate.update("insert into user values (null,?,?,?,?)",
               user.getUserName(),user.getBirthday(),user.getSex(),user.getAddress());

    }

    @Override
    public void deleteByid(Integer id) {
        jdbcTemplate.update("delete from user where id  = ?",id);
    }

    @Override
    public void updateById(User user) {
        jdbcTemplate.update("update user set username  = ?,sex = ? where id = ?",
                user.getUserName(),user.getSex(),user.getId());
    }

    @Override
    public List<User> getAll() {
//JdbcTemplate的query()方法:得到list集合
        return jdbcTemplate.query("select * from user",new BeanPropertyRowMapper<User>(User.class));

    }

    @Override
    public User getById(Integer id) {
        //JdbcTemplate的queryForObject()方法:得到一个对象
        return jdbcTemplate.queryForObject("select * from user where id = ?",
                new BeanPropertyRowMapper<User>(User.class),id);
    }


}

UserService

package com.nuo.service;

import com.nuo.pojo.User;

import java.util.List;

public interface UserService {
    //增
    void add(User user);

    //根据id删
    void deleteByid(Integer id);

    //根据id改
    void updateById(User user);

    //查所有
    List<User> getAll();

    //根据id查
    User getById(Integer id);
}

UserServiceImpl

package com.nuo.service.impl.UserServiceImpl;

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

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public void add(User user) {
        userDao.add(user);
    }

    @Override
    public void deleteByid(Integer id) {
        userDao.deleteByid(id);
    }

    @Override
    public void updateById(User user) {
        userDao.updateById(user);
    }

    @Override
    public List<User> getAll() {
        return userDao.getAll();
    }

    @Override
    public User getById(Integer id) {
        return userDao.getById(id);
    }
}

测试类

import com.nuo.config.JavaConfig;
import com.nuo.pojo.User;
import com.nuo.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.Date;
import java.util.List;
//这里要优化就要用Spring的Test了
@RunWith(SpringJUnit4ClassRunner.class)
//读取配置类
@ContextConfiguration(classes = JavaConfig.class)
public class UserTest {
    //测试类还是有很多重复代码。用 @Autowired优化一下
    @Autowired
    private UserService userService;

    @Test
    public void testAdd(){
        //下面两行代码仍是创建对象注入属性,所以用 @Autowired优化一下
       //ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        // UserService userService = ioc.getBean(UserService.class);
        User user = new User();
        user.setId(5);
        user.setUserName("唐僧");
        user.setBirthday(Date.valueOf("1647-01-01"));
        user.setSex("男");
        user.setAddress("嘉兴");
        userService.add(user);
    }
    @Test
    public void testDelete(){
        //这里我用的user表id是其他表的外键,故删除失败,怎么删除知道就好
        //ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
       // UserService userService = ioc.getBean(UserService.class);
        userService.deleteByid(2);
    }
    @Test
    public void testUpdate(){
        //ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
       // UserService userService = ioc.getBean(UserService.class);
        User user = new User();
        user.setUserName("沙和尚");
        user.setSex("男");
        user.setId(4);
        userService.updateById(user);

    }
    @Test
    public void testGetAll(){
        //ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
      //  UserService userService = ioc.getBean(UserService.class);
        List<User> all = userService.getAll();
        for (User user : all) {
            System.out.println("user = " + user);
        }
    }

    @Test
    public void testGetById(){
        //ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
       // UserService userService = ioc.getBean(UserService.class);
        User user = userService.getById(1);
        System.out.println("user = " + user);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值