如何使用Spring Boot一步一步搭建一个Web的基础工程……
安装Mysql
官方下载地址:https://dev.mysql.com/downloads/windows/ 自己去下载安装就行了。
新建数据库moxi和管理员表admin
CREATE TABLE `admin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`realName` varchar(45) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`phoneNumber` varchar(45) DEFAULT NULL,
`headPicture` varchar(45) DEFAULT NULL,
`addDate` date DEFAULT NULL,
`updateDate` date DEFAULT NULL,
`state` int(11) DEFAULT '0' COMMENT '1:正常\n2:冻结\n3:删除',
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`userName`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `admin` VALUES (1,'admin','admin','面皮大师',28,'17788886666','','2017-06-15','2017-06-15',1);
工程结构图如下
工程加载Mybatis和Mysql的依赖
修改pom.xml
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.foreknow</groupId>
<artifactId>moxi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>moxi</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
建Model、Dao、Service和Controller
新建package:model,新建Admin类:
package com.foreknow.model;
/**
* Created by imac on 2018/12/22.
*/
import java.sql.Date;
public class Admin {
private long id;
private String userName;
private String password;
private int age;
private String phoneNumber;
private String headPicture;
private Date addDate;
private Date updateDate;
private int state;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getHeadPicture() {
return headPicture;
}
public void setHeadPicture(String headPicture) {
this.headPicture = headPicture;
}
public Date getAddDate() {
return addDate;
}
public void setAddDate(Date addDate) {
this.addDate = addDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
@Override
public String toString() {
return "Admin [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age
+ ", phoneNumber=" + phoneNumber + ", headPicture=" + headPicture + ", addDate=" + addDate
+ ", updateDate=" + updateDate + ", state=" + state + "]";
}
}
新建package:Dao,新建AdminDao类:
package com.foreknow.dao;
import com.foreknow.model.Admin;
import java.util.List;
/**
* Created by imac on 2018/12/23.
*/
public interface AdminDao {
Admin findByNameAndPassword(Admin admin);
List<Admin> findByAdminWithPage(Admin admin, int start, int end);
int insert(Admin admin);
int updateStateById(int id);
int deleteById(int id);
}
新建mapper:创建AdminDao.xml映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.foreknow.dao.AdminDao">
<select id="findByNameAndPassword" resultType="com.foreknow.model.Admin">
SELECT * FROM admin where userName = #{userName} and password = #{password} and state = 0
</select>
<select id="findByAdminWithPage" resultType="com.foreknow.model.Admin">
SELECT * FROM admin where userName = #{userName} and password = #{password} and realName = #{realName}
</select>
<insert id="insert" parameterType="com.foreknow.model.Admin" >
INSERT INTO admin(id, userName, password, realName, age, phoneNumber, headPicture, addDate, updateDate, state) VALUES (null, #{userName}, #{password}, #{realName}, #{age}, #{phoneNumber}, #{headPicture}, now(), now(), 0)
</insert>
<update id="updateStateById" parameterType="java.lang.Integer">
UPDATE admin SET userName = #{userName}, password = #{password}, realName = #{realName}, age= #{age}, phoneNumber = #{phoneNumber}, headPicture = #{headPicture}, updateDate = now(), state = #{state} WHERE id = #{id}
</update>
<delete id="deleteById" parameterType="java.lang.Integer">
DELETE FROM admin WHERE id = #{id}
</delete>
</mapper>
新建配制文件
新建属性文件:application.properties
server.port=8082
server.servlet.context-path=/moxi
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/moxi?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username = root
jdbc.password =
#Mybatis
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
entity_package=com.foreknow.model
logging.level.com.foreknow.dao=debug
新建Mybatis核心配制文件:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--通过这个配置文件,完成mybatis与数据库的连接 -->
<configuration>
<settings>
<!--使用jdbc的getGeneratedKeys获取数据库自增主键值-->
<setting name="useGeneratedKeys" value="true"/>
<!--使用列标签替换别名 默认:true-->
<setting name="useColumnLabel" value="true" />
<!--开启驼峰命名转换:e{create_time} -> Entity{createTime}-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
新建Dao共通类
package com.foreknow.config.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.beans.PropertyVetoException;
/**
* Created by imac on 2018/5/6.
*/
@Configuration
//mapper的扫描路径
@MapperScan("com.foreknow.dao")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Bean(name = "dataSource")
public ComboPooledDataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUsername);
dataSource.setPassword(jdbcPassword);
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}
package com.foreknow.config.dao;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
/**
* Created by imac on 2018/5/6.
*/
@Configuration
public class SessionFactoryConfiguration {
@Value("${mybatis_config_file}")
private String mybatisConfigFilePath;
@Value("${mapper_path}")
private String mapperPath;
@Value("${entity_package}")
private String entityPackage;
@Autowired
private DataSource dataSource;
@Bean(name="sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
//SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
return sqlSessionFactoryBean;
}
}
新建package:service,新建AdminService接口:
package com.foreknow.service;
import com.foreknow.model.Admin;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* Created by imac on 2018/12/22.
*/
@Mapper
public interface AdminService {
Admin findByNameAndPassword(Admin admin);
List<Admin> findByAdminWithPage(Admin admin, int start, int end);
int insert(Admin admin);
int updateStateById(int id);
int deleteById(int id);
}
新建package:impl,新建AdminDaoImpl类:
package com.foreknow.service.impl;
import com.foreknow.dao.AdminDao;
import com.foreknow.model.Admin;
import com.foreknow.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by imac on 2018/12/23.
*/
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
private AdminDao adminDao;
@Override
public Admin findByNameAndPassword(Admin admin) {
return adminDao.findByNameAndPassword(admin);
}
@Override
public List<Admin> findByAdminWithPage(Admin admin, int start, int end) {
return adminDao.findByAdminWithPage(admin,start,end);
}
@Override
public int insert(Admin admin) {
return adminDao.insert(admin);
}
@Override
public int updateStateById(int id) {
return adminDao.updateStateById(id);
}
@Override
public int deleteById(int id) {
return adminDao.deleteById(id);
}
}
显示效果如下
注意
spring注解方式 idea报could not autowire
解决办法
解决方法为:file—->Project Structure,在如下的界面选择 Factors,然后删除Spring(直接右键Delete)
即可。