一直在学习Springboot
从开始的建立框架,然后用假数据,然后连接数据库。
算是把前台后台简单的传值和登录写出来了
记录一下。
首先创建数据库
因为做的比较简单
所以并没有做复杂的数据库
建了一个User的数据库
create Database orm
user orm
create table orm_user(
id integer primary key,
username NVARCHAR(200),
password NVARCHAR(200),
nicknme NVARCHAR(200)
)
创建一个表之后,直接可以生成对应的dao和xml也就是没有实现类了。
用一个软件就可以直接生成了
需要配置软件的xml
<?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:\software\lib\mysql-connector-java-5.1.21.jar" /> -->
<classPathEntry location="D:\devinstall\generator\sqljdbc42.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库链接URL、用户名、密码 -->
<!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sy" userId="sypro" password="sypro"> -->
<jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver" connectionURL="jdbc:sqlserver://localhost:1433;DatabaseName=orm" userId="sa" password="sqlserver">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="com.yun.orm.pc.user.domain" targetProject="D:\devinstall\generator\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成的映射文件包名和位置 -->
<sqlMapGenerator targetPackage="com.yun.orm.pc.user.dao" targetProject="D:\devinstall\generator\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.yun.orm.pc.user.dao" targetProject="D:\devinstall\generator\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
<table tableName="orm_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
</context>
</generatorConfiguration>
然后cmd生成语句,直接就可以生成相应的dao类文件和实体类User文件了
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
自动生成User类如下
package com.yun.orm.pc.user.domain;
/**
* 用户
* <p>
* Created by 周子淏 on 2018/4/9 17:11
*/
public class User {
/**
* 1.主键
*/
private Integer id;
/**
* 2.用户名
*/
private String username;
/**
* 3.密码
*/
private String password;
/**
* 4.昵称
*/
private String nickname;
public User(Integer id, String username, String password, String nickname) {
this.id = id;
this.username = username;
this.password = password;
this.nickname = nickname;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname == null ? null : nickname.trim();
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
然后xml中是会自动生成方法的。
但是因为要写增删改查 所以方法都自己删了重写了一下。
具体的DAO类如下
package com.yun.orm.pc.user.dao;
import com.yun.orm.pc.user.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component
public interface IUserDao {
/**
* 1.插入
*/
int insert(User user);
/**
* 2.全部
*/
List<User> list();
/**
* 3.修改
*/
int update(User user);
/**
* 4.删除
*/
int delete(User user);
/**
* 5.根据id查询
*/
User getById(int id);
/**
* 6.登录
*/
User loadByUsernameAndPassword(@Param("user") User user);
}
然后对应的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.yun.orm.pc.user.dao.IUserDao">
<resultMap id="BaseResultMap" type="com.yun.orm.pc.user.domain.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="NVARCHAR"/>
<result column="password" property="password" jdbcType="NVARCHAR"/>
<result column="nickname" property="nickname" jdbcType="NVARCHAR"/>
</resultMap>
<insert id="insert" parameterType="com.yun.orm.pc.user.domain.User">
insert into orm_user
(username,
password,
nickname)
values (#{username,jdbcType=NVARCHAR},
#{password,jdbcType=NVARCHAR},
#{nickname,jdbcType=NVARCHAR})
</insert>
<select id="list" resultMap="BaseResultMap">
select *
from orm_user
</select>
<select id="getbyid" resultMap="BaseResultMap">
select *
from orm_user
where id = #{id,jdbcType=INTEGER}
</select>
<select id="loadByUsernameAndPassword" resultMap="BaseResultMap">
select *
from orm_user
where username = #{user.username,jdbcType=NVARCHAR}
and password = #{user.password,jdbcType=NVARCHAR}
</select>
<update id="update" parameterType="com.yun.orm.pc.user.domain.User">
update orm_user
set username = #{username,jdbcType=NVARCHAR},
password = #{password,jdbcType=NVARCHAR},
nickname = #{nickname,jdbcType=NVARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<delete id="delete" parameterType="com.yun.orm.pc.user.domain.User">
delete from orm_user
where id = #{id,jdbcType=INTEGER}
</delete>
</mapper>
需要配置几个文件 这是在config下的
image.png
MasterDataSourceConfig类
package com.yun.orm.config.ds;
import com.yun.orm.config.properties.MasterDataSourceProperties;
import com.yun.orm.config.utils.MyUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.annotation.Resource;
import javax.sql.DataSource;
/**
* 主数据源配置文件
* <p>
* Created by 周子淏 on 2018/4/9 16:39
*/
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {MasterDataSourceConfig.PACKAGE1}, sqlSessionFactoryRef = MasterDataSourceConfig.NAME + "SqlSessionFactory")
public class MasterDataSourceConfig {
@Resource
private MasterDataSourceProperties masterDataSourceProperties;
// 精确到 master 目录,以便跟其他数据源隔离
//dao目录
static final String PACKAGE1 = "com.yun.orm.pc.*.dao";
//xml目录
private static final String mapperLocation1 = "classpath:com/yun/orm/pc/*/dao/*.xml";
private static final String[] mapperLocations = {mapperLocation1};
//全局名字前缀
static final String NAME = "master";
//数据源
@Bean(name = NAME + "DataSource")
@Primary
public DataSource dataSource() {
return MyUtils.getDruidDataSource(
masterDataSourceProperties.getDriverClassName(),
masterDataSourceProperties.getUrl(),
masterDataSourceProperties.getUsername(),
masterDataSourceProperties.getPassword());
}
//事务管理器
@Bean(name = NAME + "TransactionManager")
@Primary
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
//工厂
@Bean(name = NAME + "SqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier(NAME + "DataSource") DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setMapperLocations(MyUtils.resolveMapperLocations(mapperLocations));
return sessionFactory.getObject();
}
}
MasterDataSourceProperties类
package com.yun.orm.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 主数据源属性文件-本地sql server
* <p>
* Created by 周子淏 on 2018/4/9 16:32
*/
@Component
@ConfigurationProperties(prefix = "spring.datasource.master")
public class MasterDataSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
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;
}
}
MyUtils类
package com.yun.orm.config.utils;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 工具类
* <p>
* Created by 周子淏 on 2018/4/9 16:41
*/
public class MyUtils {
public static DruidDataSource getDruidDataSource(String driverClassName, String url, String username, String password) {
DruidDataSource dataSource = new DruidDataSource();
//这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName
dataSource.setDriverClassName(driverClassName);
//连接数据库的url
dataSource.setUrl(url);
//连接数据库的用户名
dataSource.setUsername(username);
//连接数据库的密码
dataSource.setPassword(password);
//初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
dataSource.setInitialSize(1);
//最小连接池数量
dataSource.setMinIdle(1);
//最大连接池数量
dataSource.setMaxActive(20);
//获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
dataSource.setMaxWait(1000);
return dataSource;
}
/**
* org.mybatis.spring.boot.autoconfigure包下MybatisProperties里面的方法直接拿来用
*
* @param mapperLocations xml路径数组
* @return 资源数组
*/
public static Resource[] resolveMapperLocations(String[] mapperLocations) {
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
List<Resource> resources = new ArrayList();
if (mapperLocations != null) {
String[] var3 = mapperLocations;
int var4 = var3.length;
for (int var5 = 0; var5 < var4; ++var5) {
String mapperLocation = var3[var5];
try {
Resource[] mappers = resourceResolver.getResources(mapperLocation);
resources.addAll(Arrays.asList(mappers));
} catch (IOException var8) {
;
}
}
}
return resources.toArray(new Resource[resources.size()]);
}
}
新建一个application.yml
spring:
datasource:
master:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://localhost:1433;DatabaseName=orm
username: sa
password: sqlserver
meavn中的配置如下,用的是阿里巴巴的数据源。
<?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.yun</groupId>
<artifactId>orm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>orm</name>
<description>orm project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!– set thymeleaf version –>
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>-->
<!-- <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.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>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 阿里巴巴数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!-- 扫描src/main/java下面的xml文件. -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
我在dao中一共声明了6个方法。
package com.yun.orm.pc.user.dao;
import com.yun.orm.pc.user.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component
public interface IUserDao {
/**
* 1.插入
*/
int insert(User user);
/**
* 2.全部
*/
List<User> list();
/**
* 3.修改
*/
int update(User user);
/**
* 4.删除
*/
int delete(User user);
/**
* 5.根据id查询
*/
User getById(int id);
/**
* 6.登录
*/
User loadByUsernameAndPassword(@Param("user") User user);
}
具体作用已经备注了。
然后特别说一下第6个。
@Param这是传参的一种办法。
DAO层传参 不仅仅是单纯的String Int
需要加上@Param
这样参数才可以传到.xml文件中。
然后是xml中的方法
package com.yun.orm.pc.user.service;
import com.yun.orm.pc.user.domain.User;
import java.util.List;
/**
* Created by 周子淏 on 2018/4/10 8:56
*/
public interface IUserService {
/**
* 1.插入
*/
int insert(User user);
/**
* 2.全部
*/
List<User> list();
/**
* 3.修改
*/
int update(User user);
/**
* 4.删除
*/
int delete(User user);
/**
* 5.根据id查询
*/
User getById(int id);
/**
* 6.登录
*/
Boolean isLogin(User user);
}
这里基本前边的方法和dao层调用的方法是一样的,只有最后一个判断登录的使用的是boolean的返回值,这里对于登录的判断是通过用户名和密码来查找用户是否存在,然后来判断登录是否成功。开始是想用根据用户名来查询密码这种方法,但是很明显时有弊端的,直接通过true false来对登录进行判断。
然后是service的实现类
package com.yun.orm.pc.user.service;
import com.yun.orm.pc.user.dao.IUserDao;
import com.yun.orm.pc.user.domain.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by 周子淏 on 2018/4/10 8:57
*/
@Service
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
@Override
public int insert(User user) {
return userDao.insert(user);
}
@Override
public List<User> list() {
return userDao.list();
}
@Override
public int update(User user) {
return userDao.update(user);
}
@Override
public int delete(User user) {
return userDao.delete(user);
}
@Override
public User getById(int id) {
return userDao.getById(id);
}
/**
* 6.登录
*/
@Override
public Boolean isLogin(User user) {
User user1 = userDao.loadByUsernameAndPassword(user);
if (user1 == null) {
return false;
}
return true;
}
}
这样后台的方法基本写完了 ,可以在test写几个测试类测试一下。
连接前台的话,就需要controller了。
package com.yun.orm.pc.user.web;
import com.yun.orm.pc.user.domain.User;
import com.yun.orm.pc.user.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
/**
* Created by 周子淏 on 2018/4/10 9:01
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
public IUserService userService;
@GetMapping("/index")
public String getUsers(Model model) {
/* List<User> userList=new ArrayList<>();*/
model.addAttribute("userList", userService.list());
return "/user/index";
}
@GetMapping("/add")
public String addNetClasses(Model model) {
model.addAttribute("userList", new User());
return "/user/add";
}
@PostMapping("/add")
public String addNetClasses(User user) {
userService.insert(user);
return "redirect:index";
}
@GetMapping("/{id}/update")
public String update(@PathVariable("id") Integer id, Model model) {
model.addAttribute("user", userService.getById(id));
System.out.println(id);
return "/User/update";
}
@PostMapping("/update")
public String update(User user) {
userService.update(user);
return "redirect:/user/index";
}
@GetMapping("/{id}/delete")
public String delete(@PathVariable("id") Integer id, User user, Model model) {
userService.delete(user);
return "redirect:/user/index";
}
@GetMapping("/login")
public String login(Model model) {
model.addAttribute("userList", new User());
return "/user/login";
}
@PostMapping("/login")
public String login(User user) {
Boolean isLogin = userService.isLogin(user);
if (isLogin) {
return "redirect:/user/index";
} else {
return "redirect:/user/login";
}
}
/* @PostMapping("/login")
public String login(User user, HttpServletRequest request, HttpSession session){
String username = request.getParameter("username");
String password = request.getParameter("password");
user=userService.login(username,password);
if (user!=null){
return "/user/index";
}
else{
session.setAttribute("error","账号或者密码错误,请重新输入!");
}
return "/user/login";
}*/
}
controller的配置之前也写过很多了。对应着不同的方法。
controller写好后,在前台对应上就行了。
先写的是登录
要达到的效果是,首先登录,然后登录后到index界面可以看到所有信息,
点击新增可以添加信息。添加后返回主页,然后点击修改、删除都可以完成相应操作。
- login.html
具体的代码如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
<h1>欢迎登录</h1>
<a th:href="@{/user/add}"><input type="submit" value="新增用户"></a>
<table border="1">
<tr th:each="list:${userList}">
<td th:text="${list.id}"></td>
<td th:text="${list.username}"></td>
<td th:text="${list.password}"></td>
<td th:text="${list.nickname}"></td>
<td><a th:href="@{/user/{id}/update(id=${list.Id})}">修改</a></td>
<td><a th:href="@{/user/{id}/delete(id=${list.Id})}">删除</a></td>
</tr>
</table>
</center>
</body>
</html>
*add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form action="#" th:action="@{/user/add}" th:object="${userList}" method="post">
<label>姓名</label><input type="text" th:field="*{username}"/><br>
<label>密码</label><input type="text" th:field="*{password}"/><br>
<label>昵称</label><input type="text" th:field="*{nickname}"/><br>
<input type="submit" value="添加"/>
</form>
</div>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>好的</h1>
<!--<form action="#" th:action="@{/User/update}" th:object="${userList}" method="post">
<input type="text" th:field="*{password}" /><br>
<input type="text" th:field="*{nickname}" /><br>
<input type="submit" value="确认修改"/>
</form>-->
<form action="#" th:action="@{/user/update}" th:object="${user}" method="post">
<input type="hidden" th:field="*{id}">
<input type="text" th:field="*{username}"/>
<input type="text" th:field="*{password}"/>
<input type="text" th:field="*{nickname}"/>
<input type="submit" value="确认修改"/>
</form>
</body>
</html>
delete.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="#" th:action="@{/user/delete}" th:object="${user}" method="post">
<input type="text" th:field="*{password}" /><br>
<input type="text" th:field="*{nickname}" /><br>
<input type="submit" value="确认修改"/>
</form>
</body>
</html>
这样整个的系统就完事了。
网友评论