Spring框架基於註解開發CRUD詳解

Spring框架基於註解開發CRUD,供大傢參考,具體內容如下

1. Maven坐標

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<!-- SpringJDBC jar包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<!-- spring整合junit jar包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.0.RELEASE</version>
    <scope>test</scope>
</dependency>
<!--  Lombok jar包 -->
<dependency>
    <scope>compile</scope>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.16</version>
</dependency>
<!--單元測試jar包-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<!-- mysql數據庫jar包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
    <scope>runtime</scope>
</dependency>

2. 實體類

@Data
@Component
//等價於 <bean id="user" class="org.westos.pojo.User"/>
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
}

3. Spring配置類

用於代替原來的SpringIOC

@Configuration
@ComponentScan(value = "org.westos")
@PropertySource("classpath:jdbcConfig.properties")
public class MyConfig {
    @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("dataSource")
    public DataSource createDataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    @Bean("jdbcTemplate")
    //註入JDBCtemplate模板
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

4. 業務層代碼

接口

public interface UserService {
    //查詢所有用戶
    List<User> findAll();

    //根據id查詢用戶
    User findUserById(Integer uid);

    //保存用戶
    void save(User user);

    //更新用戶
    void update(User user);

    //刪除用戶
    void delete(Integer uid);
}

實現類

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    //查詢所有用戶
    public List<User> findAll() {
        List<User> list = userDao.findAll();
        return list;
    }

    //根據id查詢用戶
    public User findUserById(Integer uid) {
        User user = userDao.findUserById(uid);
        return user;
    }

    //保存用戶
    public void save(User user) {
        userDao.save(user);
    }

    //更新用戶
    public void update(User user) {
        userDao.update(user);
    }

    //刪除用戶
    public void delete(Integer uid) {
        userDao.delete(uid);
    }
}

5. 持久層代碼

接口

public interface UserDao {
    //查詢所有
    List<User> findAll();

    //根據id查詢
    User findUserById(Integer uid);

    //保存
    void save(User user);

    //更新
    void update(User user);

    //刪除
    void delete(Integer uid);
}

實現類

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //查詢所有
    public List<User> findAll() {
        return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<User>(User.class));
    }

    //根據id查詢
    public User findUserById(Integer uid) {
        return jdbcTemplate.queryForObject("select * from user where id=?", new BeanPropertyRowMapper<User>(User.class), uid);

    }

    //保存
    public void save(User user) {
        jdbcTemplate.update("insert into user(username,birthday,sex,address) values (?,?,?,?)", user.getUsername(), user.getBirthday(), user.getSex(), user.getAddress());
    }

    //更新
    public void update(User user) {
        jdbcTemplate.update("update user set username=?,birthday=?,sex=?,address=? where id = ?", user.getUsername(), user.getBirthday(), user.getSex(), user.getAddress(), user.getId());
    }

    //刪除
    public void delete(Integer uid) {
        jdbcTemplate.update("delete from user where id=?", uid);
    }
}

6. jdbc配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_test
jdbc.username=root
jdbc.password=123

7. 測試類代碼

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyConfig.class)
public class MyTest {
    @Autowired
    private UserService userService;
    @Autowired
    private User user;

    @Test
    public void findAllTest(){
        List<User> list = userService.findAll();
        for (User user : list) {
            System.out.println(user);
        }
    }

    @Test
    public void findUserByIdTest(){
        User user = userService.findUserById(74);
        System.out.println(user);
    }

    @Test
    public void saveUserTest(){
        user.setUsername("張三");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setAddress("西安市長安區");
        userService.save(user);
    }

    @Test
    public void updateUserTest(){
        user.setId(75);
        user.setUsername("李四");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setAddress("西安市雁塔");
        userService.update(user);
    }

    @Test
    public void deleteUserTest(){
        user.setId(75);
        userService.delete(user.getId());
    }
}

8. 工程目錄

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: