您的位置:首页 > 编程语言 > Java开发

spring boot 第二课-完成单表操作及分页查询

2016-06-20 19:33 387 查看
第一部分 基本注释释意

1.前面做了一个入门例子,有了一个轻松的体验,今天来做一个模拟前后端交互的数据请求与响应的例子

如果你之前用过springmvc 的注解就很好理解了,假如没有用过就需要去看看下面这个几个注解的意思了。

@Controller  :对类名进行标识,位于Control 层,标记的类将会被spring 容器所管理,会创建一个实例(默认是单例的)每次访问都是同一个实例,是非线程安全的

@ResponseBody  :一般作用于方法上, 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。

@RestController  :是spring4的主机,是Controller 和ResponseBody的作用的合体

@RequestMapping  :http 请求的映射路径,@RequestMapping("/getlist")  public List<User> getList(){return
null;}

@RequestParam:http 请求的参数设置标识 public List<User> getList(@RequestParam("id")Long id){

@PathVariable :http 请求路径中所带参数的设置的注解

  @RequestMapping(value="/getuser/{id}")

    public User getUser(@PathVariable Long id){

        User u=new User();

        u.setId(1);

        u.setName("hering");

        u.setPassword("123456");

        map.put(1l, u);

        return u;
    }

@ModelAttribute :http://hbiao68.iteye.com/blog/1948380

第二部分:单表操作及查询分页

1.pom.xml 配置如下:

<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>com.it.guo</groupId>
<artifactId>sboot</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>sboot Maven Webapp</name>
<url>http://maven.apache.org</url>

<!-- spring-boot-starter-parent 包含了以下信息 - -->
<!-- 1、使用java6编译级别 2、使用utf-8编码 3、实现了通用的测试框架 (JUnit, Hamcrest, Mockito).
4、智能资源过滤 5、智能的插件配置(exec plugin, surefire, Git commit ID, shade). -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
<relativePath />
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring boot 核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入web 模块 需要添加 -->
<!-- http://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<!-- 开发工具 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
</dependencies>
<build>
<finalName>sboot</finalName>
<plugins>
<plugin>
<!-- 自动重动 该工程在spring boot开发过程中非常有用,当工程文件发生变化的时候工程能够自动重启生效变化的内容 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!-- <configuration> <fork>true</fork> </configuration> -->
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
2.数据库配置文件,让在resource 目录下面

spring.datasource.url=jdbc:mysql://localhost:3306/simple_service
spring.datasource.username=banana
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.format_sql=true

3.接口定义(如果加上事务就直接加在接口上面,springboot 会根据注解自动生成一个代理的实例)

package com.it.core.repository;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import com.it.core.bean.UserInfo;

@Transactional
public interface UserRepository extends PagingAndSortingRepository<UserInfo, Long>, JpaSpecificationExecutor<UserInfo> {
// 原生的mysql 也可以用jpal 面向对象的编程
@Query(value = "select u.* from userinfo u where u.name = ?1", nativeQuery = true)
UserInfo findByname(String name);

// 修改
@Modifying
@Query(value = "update UserInfo set name=?1 where name=?2")
void updateUser(String newName, String oldName);

// 删除
@Modifying
@Query(value = "delete from UserInfo where id=?1")
void delete(Integer id);

}


4.运行的类

package com.it.core.web;

import java.util.Iterator;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.it.core.bean.UserInfo;
import com.it.core.repository.UserRepository;

@EnableAutoConfiguration
@EntityScan("com.it.core.bean")
@EnableJpaRepositories("com.it.core.repository")
public class Appliation implements CommandLineRunner {
@Autowired
UserRepository userRepository;

// private EntityManager entity = null;
// new LocalContainerEntityManagerFactoryBean();
/**
* start tomcat
*
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(Appliation.class);
}

@Override
public void run(String... args) throws Exception {
// add
userRepository.save(new UserInfo("test123"));
// 查询
UserInfo u = userRepository.findByname("howell0");
if (u != null) {
System.err.println(u.getName() + "---------");
// 修改
userRepository.updateUser("howell_zhang", "howell0");
// 再次chaxun
UserInfo u1 = userRepository.findByname("howell_zhang");
System.err.println(u1.getName() + "---------");
}

// 删除
userRepository.delete(9);
// 分页
Iterator<UserInfo> i = findAllwitPage().iterator();
while (i.hasNext()) {
UserInfo o = (UserInfo) i.next();
System.err.println(o.getName() + "----");
}

}

public Page<UserInfo> findAllwitPage() {
Pageable pageable = new PageRequest(1, 20);
// 通常使用Specification 的匿名内部类,
Specification<UserInfo> specification = new Specification<UserInfo>() {
/*
* @param root:代表的查询的实体类
*
* @param query:可以从中得到Root对象,即告知JPA Criteria查询要查询哪一个实体类,
* 还可以来添加查询条件,还可以结合EntityManager对象得到最终查询的TypedQuery 对象
*
* @Param
* cb:criteriabuildre对象,用于创建Criteria相关的对象工程,当然可以从中获取到predicate类型
*
* @return:代表一个查询条件
*/
@Override
public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
// Predicate p1 = cb.like(root.get("id").as(String.class), "%" +
// "1" + "%");
Predicate p2 = cb.like(root.get("name").as(String.class), "%" + "howell" + "%");
// Predicate p3 = cb.like(root.get("email").as(String.class),
// "%s%");
// 构建组合的Predicate示例:
Predicate p = cb.and(p2);
return p;
}
};
return userRepository.findAll(specification, pageable);
}

}


5.bean 的类:(这里通过注释,不需要再手动建立数据库,实现注解,在程序启动的时候,自动创建表,创建表的模式有可以参考

application.properties 中的:#spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

spring.jpa.hibernate.ddl-auto=update 属性)

package com.it.core.bean;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="userinfo")
public class UserInfo implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id",unique=true,nullable=false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name",unique=true,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserInfo(String name) {
this.name = name;
}

public UserInfo() {

}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: