springboot入门2—jpa访问mysql数据库

还是参照官方的例子

1,maven依赖

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>springBootTestMysql</groupId>
  <artifactId>springBootTestMysql</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springBootTestMysql Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  
  <parent>
  	<groupId>org.springframework.boot</groupId>
  	<artifactId>spring-boot-starter-parent</artifactId>
  	<version>1.4.2.RELEASE</version>
  </parent>
  <properties>
        <java.version>1.8</java.version>
    </properties>
  <distributionManagement>
		<repository>
			<id>releases</id>
			<name>Releases</name>
			<url>http://10.92.1.84:8081/nexus/content/repositories/releases</url>
		</repository>
		<snapshotRepository>
			<id>snapshots</id>
			<name>Snapshots</name>
			<url>http://10.92.1.84:8081/nexus/content/repositories/snapshots</url>
		</snapshotRepository>
	</distributionManagement>

	<repositories>
		<repository>
			<id>public</id>
			<url>http://10.92.1.84:8081/nexus/content/groups/public</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>libs-central</id>
			<name>libs-releases</name>
			<url>http://10.92.35.161/nexus/content/repositories/releases</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>libs-snapshots</id>
			<name>libs-snapshots</name>
			<url>http://10.92.35.161/nexus/content/repositories/snapshots</url>
			<snapshots />
		</repository>
		<repository>
			<id>15public</id>
			<name>i5public</name>
			<url>http://10.92.7.15:8081/nexus/content/repositories/public/</url>
		</repository>
		</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>public</id>
			<url>http://10.92.1.84:8081/nexus/content/groups/public</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>
	
	
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-web</artifactId>  
        
    </dependency>  
      
     <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->  
  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-data-jpa</artifactId>  
           
        </dependency>  
  
        <!-- Use MySQL Connector-J -->  
  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
          
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-test</artifactId>  
           
            <scope>test</scope>  
        </dependency>  
  </dependencies>
  <build>
    <finalName>springBootTestMysql</finalName>
  </build>
</project>


2,创建mysql数据库,由于我本机没安装mysql,这里使用docker,来创建一个mysql容器,随时可以删掉

a.直接使用mysql的官方镜像使用  docker pull mysql 命令,下载镜像

b.pull完成之后,直接run起来,run的时候可以使用-e参数制定mysql的root用户的密码 , docker run -d -p3306:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql mysql:1.0

c.进入mysql容器,建数据库,建表,  mysql -h ip -uusername -ppassword -P端口

3.In the sources folder, you create a resource file src/main/resources/application.properties

创建连接数据库所需要的properties文件,主要就是连接的地址啊,用户名,密码

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
4. 创建实体类

/**
 * Copyright EXPRESS PAY 2017, Inc. All rights reserved.
 */
/**
 * 
 */

package hello.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * <p>
 * TODO。
 * </p>
 *
 * @author lujia
 * @version 1.0 
 * @date 2017年7月11日
 */
@Entity   //This tells Hibernate to make a table out of this class
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String sex;
    /** 
     * 获取 id
     * @return id
     */
    public int getId() {
        return id;
    }
    /** 
     * 设置 id
     * @param id id
     */
    public void setId(int id) {
        this.id = id;
    }
    /** 
     * 获取 name
     * @return name
     */
    public String getName() {
        return name;
    }
    /** 
     * 设置 name
     * @param name name
     */
    public void setName(String name) {
        this.name = name;
    }
    /** 
     * 获取 sex
     * @return sex
     */
    public String getSex() {
        return sex;
    }
    /** 
     * 设置 sex
     * @param sex sex
     */
    public void setSex(String sex) {
        this.sex = sex;
    }
    
    
}

5.创建 reository

/**
 * Copyright EXPRESS PAY 2017, Inc. All rights reserved.
 */
/**
 * 
 */

package hello.repository;

import org.springframework.data.repository.CrudRepository;

import hello.model.User;

/**
 * <p>
 * TODO。
 * </p>
 *
 * @author lujia
 * @version 1.0 
 * @date 2017年7月11日
 */

//This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
//CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User , Long>{

    
}

6.创建controller


/**
 * Copyright EXPRESS PAY 2017, Inc. All rights reserved.
 */
/**
 * 
 */

package lujia.springboot.hello;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * TODO。
 * </p>
 *
 * @author lujia
 * @version 1.0 
 * @date 2017年7月12日
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;
    
    @RequestMapping("/add")
    @ResponseBody
    public String addUser(@RequestParam String name,@RequestParam String sex){
        User user=new User();
        user.setName(name);
        user.setSex(sex);
        userRepository.save(user);
        return "add user";
    }
  
    
    @RequestMapping("/getAllUsers")
    public @ResponseBody Iterable<User> getAllUsers() {
        
        return userRepository.findAll();
    }
}

7.启动类

/**
 * Copyright EXPRESS PAY 2017, Inc. All rights reserved.
 */
/**
 * 
 */

package lujia.springboot.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * <p>
 * TODO。
 * </p>
 *
 * @author lujia
 * @version 1.0 
 * @date 2017年7月12日
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

直接运行启动类,springboot内置的tomcat默认开启8080端口访问, 这里有个坑,来看下@SpringBootApplication 注解,

/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;

/**
 * Indicates a {@link Configuration configuration} class that declares one or more
 * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
 * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience
 * annotation that is equivalent to declaring {@code @Configuration},
 * {@code @EnableAutoConfiguration} and {@code @ComponentScan}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 1.2.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))
//@ComponentScan 默认扫描的是我们启动类同个包或者子包下的类,
public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	Class<?>[] exclude() default {};


}
@ComponentScan 默认扫描的是我们启动类同个包或者子包下的类,刚开始不在一个包下,搞了半天,

8.测试




9 ,在项目基础上添加日志,使用logback

直接在 src/main/resources目录下,新建logback.xml

	<configuration>
		<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->
		<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
			<encoder>
				<pattern>%d %p (%file:%line\)- %m%n</pattern>
				<charset>UTF-8</charset>
			</encoder>
		</appender>
		<appender name="baselog"
			class="ch.qos.logback.core.rolling.RollingFileAppender">
			<File>E:\log\base.log</File>
			<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
				<fileNamePattern>base.log.%d.%i</fileNamePattern>
				<timeBasedFileNamingAndTriggeringPolicy
					class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
					<!-- or whenever the file size reaches 64 MB -->
					<maxFileSize>64 MB</maxFileSize>
				</timeBasedFileNamingAndTriggeringPolicy>
			</rollingPolicy>
			<encoder>
				<pattern>
					%d %p (%file:%line\)- %m%n
				</pattern>
				<charset>UTF-8</charset> <!-- 此处设置字符集 -->
			</encoder>
		</appender>
		<root level="info">
			<appender-ref ref="STDOUT" />
		</root>
		<logger name="lujia.springboot.hello" level="DEBUG">
			<appender-ref ref="baselog" />
		</logger>
	</configuration>  

10.修改userController添加日志打印



测试成功,




参考了一下别人写的jpa的发现springboot结合jpa操作数据库太方便了,分页,排序,查询都非常简单方便,可以快速启动一个工程,代码如下

/**
 * Copyright EXPRESS PAY 2017, Inc. All rights reserved.
 */
/**
 * 
 */

package lujia.springboot.hello.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import lujia.springboot.hello.model.Language;

/**
 * <p>
 * </p>
 *
 * @author lujia
 * @version 1.0 
 * @date 2017年7月13日
 */
@Repository
public interface LanguageRepository extends JpaRepository<Language, Long>{

    
    List<Language> findByName(String name);
    List<Language> findByAge(String age);
    List<Language> findByNameAndAge(String name,String age);
    @Query("select l from Language l where l.name=:name and l.age=:age")
    List<Language> withNameAndAge(@Param("name")String name,@Param("age")String age);
    @Query("select l from Language l where l.id>:id")
    List<Language> withID(@Param("id")Long id);
}

/**
 * Copyright EXPRESS PAY 2017, Inc. All rights reserved.
 */
/**
 * 
 */

package lujia.springboot.hello.web;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import lujia.springboot.hello.model.Language;
import lujia.springboot.hello.repository.LanguageRepository;

/**
 * <p>
 * </p>
 *
 * @author lujia
 * @version 1.0 
 * @date 2017年7月13日
 */
@RestController
@RequestMapping("/language")
public class LanguageController {

    private static Logger logger=LoggerFactory.getLogger(LanguageController.class);
    @Autowired
    private LanguageRepository languageRepository;
    
    @RequestMapping("/save")
    @ResponseBody
    public String save(String name,String age){
        logger.debug("save 开始");
        Language save = languageRepository.save(new Language(null,name,age));
        
        logger.debug("save 结束");
        return "save id="+save.getId();
    }
    @RequestMapping("/quesyByName")
    @ResponseBody
    public List<Language> quesyByName(String name){
        logger.debug("quesyByName 开始");
        List<Language> findByName = languageRepository.findByName(name);
        
        logger.debug("quesyByName 结束");
        return findByName;
    }
    @RequestMapping("/quesyByAge")
    @ResponseBody
    public List<Language> quesyByAge(String age){
        logger.debug("quesyByAge 开始");
        List<Language> quesyByAge = languageRepository.findByAge(age);
        
        logger.debug("quesyByAge 结束");
        return quesyByAge;
    }
    
    @RequestMapping("/quesyByNameAndAge")
    @ResponseBody
    public List<Language> quesyByNameAndAge(String name,String age){
        logger.debug("quesyByNameAndAge 开始");
        List<Language> lsit = languageRepository.findByNameAndAge(name, age);
        
        logger.debug("quesyByNameAndAge 结束");
        return lsit;
    }
    @RequestMapping("/withNameAndAge")
    @ResponseBody
    public List<Language> withNameAndAge(String name,String age){
        logger.debug("quesyByNameAndAge 开始");
        List<Language> lsit = languageRepository.withNameAndAge(name, age);
        
        logger.debug("quesyByNameAndAge 结束");
        return lsit;
    }
    @RequestMapping("/withID")
    @ResponseBody
    public List<Language> withID(Long id){
        logger.debug("withID 开始");
        List<Language> lsit = languageRepository.withID(id);
        
        logger.debug("withID 结束");
        return lsit;
    }
    
    @RequestMapping("/sort")
    @ResponseBody
    public List<Language> sort(){
        logger.debug("sort 开始");
        List<Language> lsit = languageRepository.findAll(new Sort(Direction.ASC, "age"));
        
        logger.debug("sort 结束");
        return lsit;
    }
    @RequestMapping("/page")
    @ResponseBody
    public Page<Language> page(int page,int size){
        logger.debug("page 开始");
       Page<Language> findAll = languageRepository.findAll(new PageRequest(page, size));
      
        logger.debug("page 结束");
        return findAll;
    }
    
    
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值