先看完教程,想着做项目去学的。
环境结构
idea:IntelliJ IDEA 2021.2.4 idea开发spring要比普通版本的eclipse方便的多,很多环境只需要设置即可 spring开发一般和maven搭配使用,maven可以自动拉取需要的库,方便开发
注意:一般maven设置的是国内镜像,虽然快,但是不全。所以可能拉取以后,有的属性会报错说没有找到,但一般这些属性也不会用,所以删除即可,具体入门改留哪些属性下面再说
创建项目
步骤 1.下载idea专业版 2021.2.4(2022版本不能pj,这里不讲pj) 2.下载maven3.6(高版本不支持喔) 3.打开idea,选择创建spring 一定注意java版本 4.选择插件
5.在设置里面搜索maven,添加自己下的maven的主路径和配置文件(安装maven还需要修改配置文件,具体搜索spring maven安装教程) 配置好以后如果是第一次配置,就会在右下角看到拉取的库
如果不出意外的话会出意外,打开pom.xml会看到很多错误,就是上面说库不全的原因 我们留下一下配置:(这是我基于mysql配置留下的属性喔,还有注意java版本一定配置对maven.compiler.source)
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>demo1</description>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
<classifier>${repackage.classifier}</classifier>
<image>
<builder>paketobuildpacks/builder:tiny</builder>
<env>
<BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
</env>
</image>
</configuration>
</plugin>
</plugins>
</build>
</project>
我也不太看得懂,但是配置某样东西的时候一般有xml的说明
连接数据库
没有控制层,就一个dao,一个user,一个userservicel。
dao层为持久层,entity是实体,就是存数据的Javabean,service是业务层,负责处理数据,和mvc的控制器一样,也经常命名为Controller。
JdbcTemplate 是 Spring JDBC 核心包(core)中的核心类,它可以通过配置文件、注解、Java 配置类等形式获取数据库的相关信息,实现了对 JDBC 开发过程中的驱动加载、连接的开启和关闭、SQL 语句的创建与执行、异常处理、事务处理、数据类型转换等操作的封装。我们只要对其传入SQL 语句和必要的参数即可轻松进行 JDBC 编程。
实体:
package com.example.demo.entity;
public class User {
private Integer userId;
private String userName;
private String status;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", status='" + status + '\'' +
'}';
}
}
dao层(接口不展示了)
package com.example.demo.dao.impl;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
@Resource
private JdbcTemplate jdbcTemplate;
@Override
public int addUer(User user) {
String sql = "INSERT into `user` (`user`.user_name,`user`.`status`) VALUES(?,?);";
int update = jdbcTemplate.update(sql, user.getUserName(), user.getStatus());
return update;
}
@Override
public int update(User user) {
String sql = "UPDATE `user` SET status=? WHERE user_name=?;";
return jdbcTemplate.update(sql, user.getStatus(), user.getUserName());
}
@Override
public int delete(User user) {
String sql = "DELETE FROM `user` where user_name=?;";
return jdbcTemplate.update(sql, user.getUserName());
}
@Override
public int count(User user) {
String sql = "SELECT COUNT(*) FROM `user` where `status`=?;";
return jdbcTemplate.queryForObject(sql, Integer.class, user.getStatus());
}
@Override
public List<User> getList(User user) {
String sql = "SELECT * FROM `user` where `status`=?;";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class), user.getStatus());
}
@Override
public User getUser(User user) {
String sql = "SELECT * FROM `user` where `user_id`=?;";
return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), user.getUserId());
}
@Override
public void batchAddUser(List<Object[]> batchArgs) {
String sql = "INSERT into `user` (`user`.user_name,`user`.`status`) VALUES(?,?);";
jdbcTemplate.batchUpdate(sql, batchArgs);
}
}
业务层(其实这里也没做啥业务,主要是说明一下,这里可以做逻辑业务):
package com.example.demo.service.impl;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public int addUser(User user) {
return userDao.addUer(user);
}
@Override
public int updateUser(User user) {
return userDao.update(user);
}
@Override
public int deleteUser(User user) {
return userDao.delete(user);
}
@Override
public int countUser(User user) {
return userDao.count(user);
}
@Override
public List<User> getUserList(User user) {
return userDao.getList(user);
}
@Override
public User getUser(User user) {
return userDao.getUser(user);
}
@Override
public void batchAddUser(List<Object[]> batchArgs) {
userDao.batchAddUser(batchArgs);
}
}
主类:
package com.example.demo;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
public class Demo1Application {
public static void main(String[] args) {
ApplicationContext context2 = new ClassPathXmlApplicationContext("Beans.xml");
UserService userService = context2.getBean("userService", UserService.class);
User user = new User();
user.setUserName("小张");
user.setStatus("离线");
int i = userService.addUser(user);
System.out.println("新增用户成功!");
User user1 = new User();
user1.setUserName("小张");
user1.setStatus("在线");
int u = userService.updateUser(user1);
System.out.println("修改用户成功");
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"小明", "在线"};
Object[] o2 = {"小龙", "离线"};
Object[] o3 = {"小林", "在线"};
Object[] o4 = {"小李", "在线"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
batchArgs.add(o4);
userService.batchAddUser(batchArgs);
System.out.println("批量增加完毕");
User user2 = new User();
user2.setStatus("在线");
int i1 = userService.countUser(user2);
System.out.println("在线用户的个数为:" + i1);
List<User> userList = userService.getUserList(user2);
System.out.println("在线用户列表查询成功!");
for (User user4 : userList) {
System.out.println("用户 ID:" + user4.getUserId() + ",用户名:" + user4.getUserName() + ",状态:" + user4.getStatus());
}
}
}
Beans.xml
```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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.example.demo"></context:component-scan>
<!--引入 jdbc.properties 中的配置-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--定义数据源 Bean-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--数据库连接地址-->
<property name="url" value="${jdbc.url}"/>
<!--数据库的用户名-->
<property name="username" value="${jdbc.username}"/>
<!--数据库的密码-->
<property name="password" value="${jdbc.password}"/>
<!--数据库驱动-->
<property name="driverClassName" value="${jdbc.driver}"/>
</bean>
<!--定义JdbcTemplate Bean-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--将数据源的 Bean 注入到 JdbcTemplate 中-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:// 192.168.101.121:3306/spring_jdbc_db
jdbc.username=root
jdbc.password=123
结果:
```bash
新增用户成功!
00:12:15.865 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL update
00:12:15.865 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL statement [UPDATE `user` SET status=? WHERE user_name=?;]
00:12:15.865 [main] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
00:12:15.865 [main] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql:// 192.168.101.121:3306/spring_jdbc_db]
修改用户成功
00:12:15.883 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing SQL batch update [INSERT into `user` (`user`.user_name,`user`.`status`) VALUES(?,?);]
00:12:15.884 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL statement [INSERT into `user` (`user`.user_name,`user`.`status`) VALUES(?,?);]
00:12:15.884 [main] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
00:12:15.884 [main] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql:// 192.168.101.121:3306/spring_jdbc_db]
00:12:15.900 [main] DEBUG org.springframework.jdbc.support.JdbcUtils - JDBC driver supports batch updates
批量增加完毕
00:12:15.919 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL query
00:12:15.920 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL statement [SELECT COUNT(*) FROM `user` where `status`=?;]
00:12:15.920 [main] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
00:12:15.920 [main] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql:// 192.168.101.121:3306/spring_jdbc_db]
在线用户的个数为:12
00:12:15.972 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL query
00:12:15.972 [main] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL statement [SELECT * FROM `user` where `status`=?;]
00:12:15.972 [main] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
00:12:15.972 [main] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql:// 192.168.101.121:3306/spring_jdbc_db]
00:12:15.986 [main] DEBUG org.springframework.jdbc.core.BeanPropertyRowMapper - Mapping column 'user_id' to property 'userId' of type 'java.lang.Integer'
00:12:15.988 [main] DEBUG org.springframework.jdbc.core.BeanPropertyRowMapper - Mapping column 'user_name' to property 'userName' of type 'java.lang.String'
00:12:15.988 [main] DEBUG org.springframework.jdbc.core.BeanPropertyRowMapper - Mapping column 'status' to property 'status' of type 'java.lang.String'
在线用户列表查询成功!
用户 ID:6,用户名:小张,状态:在线
用户 ID:7,用户名:小明,状态:在线
用户 ID:9,用户名:小林,状态:在线
用户 ID:10,用户名:小李,状态:在线
用户 ID:11,用户名:小张,状态:在线
用户 ID:12,用户名:小明,状态:在线
用户 ID:14,用户名:小林,状态:在线
用户 ID:15,用户名:小李,状态:在线
用户 ID:16,用户名:小张,状态:在线
用户 ID:17,用户名:小明,状态:在线
用户 ID:19,用户名:小林,状态:在线
用户 ID:20,用户名:小李,状态:在线
进程已结束,退出代码为 0
这是没有配服务器的状态,所以采用的主类打印
下一节将学如何构建web目录和配置servlet
|