文章目录
第一个springboot项目
新建一个普通maven项目
创建pom文件,下面用的是2.3.11版本。
<?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>org.bruce</groupId>
<artifactId>springbootstudy</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.11.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
为了完成应用程序,我们需要创建一个单独的java文件。Maven默认会变异src/main/java下的源码。
新建:com.bruce.Application 作为程序的入口
package com.bruce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//这个注解会扫描该类级别下面的所有包,所以建议把main应用类
//放在位于其他类上面的根包中。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
注意事项
通常建议将main应用类放在位于其他类上面的根包(root package)中。一个典型的包结构。
集成mybatis
建表
CREATE TABLE `tmall_user` (
`id` int NOT NULL AUTO_INCREMENT ,
`passwd` varchar(255) NULL ,
`username` varchar(255) NULL ,
PRIMARY KEY (`id`)
);
添加mybatis和mysql依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 添加mybatis生成器-->
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
</plugin>
</plugins>
</build>
在controller新建UserController
package com.bruce.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping("/hello")
public Object sayHello(){
return "hello";
}
}
生成mapper
在resources目录,新建application.yml文件,增加内容如下
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot?serverTimezone=GMT%2B8
username: root
password: 1234546
mybatis:
mapper-locations: classpath:mapping/*.xml #mapper文件的位置
准备mybatis的生成文件generatorConfig.xml,并在相应目录创建好model,dao,mapping文件。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="D:\maven\repository\mysql\mysql-connector-java\8.0.25\mysql-connector-java-8.0.25.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/springboottest" userId="root" password="yuan123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.bruce.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.bruce.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="tmall_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
双击生成对应的文件如下图:
注意:得再Application 启动类上增加@MapperScan扫描注解
@SpringBootApplication
@MapperScan(basePackages = {"com.bruce.dao"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在UserMapper中添加一个方法
User findByUserNameAndPasswd(String username, String passwd);
相应的到UserMapper.xml文件中添加该方法
<select id="findByUserNameAndPasswd" resultType="com.bruce.model.User" parameterType="map">
select
<include refid="Base_Column_List" />
from tmall_user where 1=1
<if test="passwd != null" >
and passwd = #{passwd,jdbcType=VARCHAR}
</if>
<if test="username != null" >
and username = #{username,jdbcType=VARCHAR}
</if>
limit 1
</select>
单元测试
要测试刚才新增的Mapper方法是否成功,这里需要单元测试,在springboot中是有专门的组件来做单元测试的,在pom文件中新增依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
新建UserTest类放置在test目录下
//如果有多个启动类的话,需要指定跑哪个测试
@SpringBootTest(classes = {Application.class})
@RunWith(SpringRunner.class)
public class UserTest {
@Resource
private UserMapper userMapper;
@Test
public void testAdd() {
User user = new User() ;
user.setPasswd("123");
user.setUsername("lili");
userMapper.insertSelective(user);
}
@Test
public void testFindUser() {
User enjoy = userMapper.findByUserNameAndPasswd("lili", "123");
System.out.println(enjoy);
}
}
新建IUseService在service目录下
public interface IUserService {
boolean login(String username,String passwd);
boolean register(String username,String passwd);
}
创建实现类
@Service
public class UserServiceImpl implements IUserService {
@Resource
private UserMapper userMapper;
@Override
public boolean login(String username, String passwd) {
User user = userMapper.findByUserNameAndPasswd(username, passwd);
return user != null;
}
@Override
public boolean register(String username, String passwd) {
User user = new User() ;
user.setPasswd(passwd);
user.setUsername(username);
int i = userMapper.insertSelective(user);
return i > 0;
}
}
修改controller
@RestController
public class UserController {
@Resource
private IUserService iUserService;
@RequestMapping("/hello")
public Object sayHello(){
return "hello";
}
@RequestMapping("/login")
public String login(String username,String passwd) {
boolean login = iUserService.login(username, passwd);
if(login) {
return "登陆成功";
}else {
return "登陆失败";
}
}
@RequestMapping("/register")
public String register(String username,String passwd) {
boolean login = iUserService.register(username, passwd);
if(login) {
return "注册成功";
}else {
return "注册失败";
}
}
}
在浏览器上输入:localhost:8080/register?username=jack&passwd=123,显示“注册成功”
在浏览器上输入:localhost:8080/login?username=lili&passwd=123,显示“登陆成功”