SpringBoot+MySQL+c3p0项目搭建
程序员文章站
2024-03-20 08:54:10
...
参考
http://www.jb51.net/article/124077.htm (详解springboot 使用c3p0数据库连接池的方法)
结构
数据库需要自己创建,项目中没有写Service层
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`userName` varchar(32) DEFAULT NULL COMMENT '用户名',
`passWord` varchar(32) DEFAULT NULL COMMENT '密码',
`user_sex` varchar(32) DEFAULT NULL,
`nick_name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
代码
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>
<groupId>com.jxust</groupId>
<artifactId>springboot-mybatis-xml</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-mybatis-xml</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#spring.datasource.driverClassName = com.mysql.jdbc.Driver
#spring.datasource.url = jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf-8
#spring.datasource.username = root
#spring.datasource.password = root
#mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf-8&useSSL=true
c3p0.user=root
c3p0.password=root
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.minPoolSize=2
c3p0.maxPoolSize=10
c3p0.maxIdleTime=1800000
c3p0.acquireIncrement=3
c3p0.maxStatements=1000
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=60
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
c3p0.breakAfterAcquireFailure=false
c3p0.testConnectionOnCheckout=false
DataSourceConfig.java
package com.jxust;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* \* Created with IntelliJ IDEA.
* \* User: Peng
* \* Date: 2018-01-22
* \* Time: 15:13
* \* Description:c3p0数据源配置
* \
*/
@Configuration
public class DataSourceConfig {
@Bean(name = "dataSource")
@Qualifier(value = "dataSource")
@Primary
@ConfigurationProperties(prefix = "c3p0")
public DataSource dataSource(){
return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
}
}
SpringbootMybatisXmlApplication.java
package com.jxust;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootMybatisXmlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisXmlApplication.class, args);
}
}
UserMapper.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.jxust.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.jxust.entity.UserEntity" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="passWord" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex" javaType="com.jxust.enums.UserSexEnum"/>
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, userName, passWord, user_sex, nick_name
</sql>
<select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
</select>
<select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.jxust.entity.UserEntity" >
INSERT INTO
users
(userName,passWord,user_sex)
VALUES
(#{userName}, #{passWord}, #{userSex})
</insert>
<update id="update" parameterType="com.jxust.entity.UserEntity" >
UPDATE
users
SET
<if test="userName != null">userName = #{userName},</if>
<if test="passWord != null">passWord = #{passWord},</if>
nick_name = #{nickName}
WHERE
id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
users
WHERE
id =#{id}
</delete>
</mapper>
mybatis-config.xml
mybatis的配置文件,项目中没有使用到
<?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">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
UserEntity.java
package com.jxust.entity;
import com.jxust.enums.UserSexEnum;
import java.io.Serializable;
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String userName;
private String passWord;
private UserSexEnum userSex;
private String nickName;
public UserEntity() {
super();
}
public UserEntity(String userName, String passWord, UserSexEnum userSex) {
super();
this.passWord = passWord;
this.userName = userName;
this.userSex = userSex;
}
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 UserSexEnum getUserSex() {
return userSex;
}
public void setUserSex(UserSexEnum userSex) {
this.userSex = userSex;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", userSex=" + userSex +
", nickName='" + nickName + '\'' +
'}';
}
}
UserSexEnum.java
package com.jxust.enums;
public enum UserSexEnum {
MAN, WOMAN
}
UserMapper.java
package com.jxust.controller;
import com.jxust.entity.UserEntity;
import com.jxust.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/getUsers")
public List<UserEntity> getUsers() {
List<UserEntity> users=userMapper.getAll();
return users;
}
@GetMapping("/getUser")
public UserEntity getUser(Long id) {
UserEntity user=userMapper.getOne(id);
return user;
}
@PostMapping("/add")
public void save(UserEntity user) {
userMapper.insert(user);
}
@PutMapping(value="update")
public void update(UserEntity user) {
userMapper.update(user);
}
@DeleteMapping(value="/delete/{id}")
public void delete(@PathVariable("id") Long id) {
userMapper.delete(id);
}
}
UserController.java
package com.jxust.controller;
import com.jxust.entity.UserEntity;
import com.jxust.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/getUsers")
public List<UserEntity> getUsers() {
List<UserEntity> users=userMapper.getAll();
return users;
}
@GetMapping("/getUser")
public UserEntity getUser(Long id) {
UserEntity user=userMapper.getOne(id);
return user;
}
@PostMapping("/add")
public void save(UserEntity user) {
userMapper.insert(user);
}
@PutMapping(value="update")
public void update(UserEntity user) {
userMapper.update(user);
}
@DeleteMapping(value="/delete/{id}")
public void delete(@PathVariable("id") Long id) {
userMapper.delete(id);
}
}
测试类
UserMapperTest.java
package com.jxust.mapper;
import com.jxust.entity.UserEntity;
import com.jxust.enums.UserSexEnum;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper UserMapper;
@Test
public void testInsert() throws Exception {
UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN));
UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));
UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));
Assert.assertEquals(3, UserMapper.getAll().size());
}
@Test
public void testQuery() throws Exception {
List<UserEntity> users = UserMapper.getAll();
if(users==null || users.size()==0){
System.out.println("is null");
}else{
System.out.println(users.toString());
}
}
@Test
public void testUpdate() throws Exception {
UserEntity user = UserMapper.getOne(29l);
System.out.println(user.toString());
user.setNickName("neo");
UserMapper.update(user);
Assert.assertTrue(("neo".equals(UserMapper.getOne(6l).getNickName())));
}
}
推荐阅读
-
6月份Github上最热门的Java开源项目
-
SpringBoot+MySQL+c3p0项目搭建
-
8月份Github上最热门的JavaScript开源项目排行
-
7月份Github上最热门的开源项目
-
10月份Github上最热门的开源项目
-
SpringMVC+JDBC快速搭建(使用注解) 博客分类: java框架
-
SpringMVC+JDBC快速搭建(使用注解) 博客分类: java框架
-
通用高速缓冲器:CMSPAD Cache 博客分类: 项目: CMSPAD CachePHPZendFlashIDEA
-
正确解决 projects cannot be imported because they already exist in the workspace eclipse工程冲突项目名冲突冲突already exist
-
TensorFlow练手项目三:使用VGG19迁移学习实现图像风格迁移