-
Spring-data-jpa:使用hibernate作为实现,基本上不需要写sql,因为sql都是统一的,总是会产生多余的查询,性能上相对而言会低,但不绝对,影响性能的因是多种的,这里说的性能是 从最终的查询的sql来对比的,毕竟生成的sql没有经过深思熟虑写出来的性能好。
创建springboot 工程 必须继承spring-boot-stater-parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<!--添加spring-mvc 依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
编写controller
@RestController public class javaController { @RequestMapping("/hello") public Map sayHello(){ Map map = new HashMap(); map.put("java","我爱java"); return map; } }
主启动类(一定要保证作为其他java类的父类)
@SpringBootApplication public class HelloApplication { public static void main(String[] args){ SpringApplication.run(HelloApplication.class,args); } }
效果:
从数据库中读取数据显示到页面上
首先编写数据库User
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
添加依赖
<!--添加springdatajpa的依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
编写application.properties
#DB Configatio spring.datasource.driver=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot spring.datasource.username=root spring.datasource.password=root #JPA Configuration spring.jpa.database=MySQL spring.jpa.show-sql=true //在控制台上可以显示 spring.jpa.generate-ddl=true //自动创建表,如果已经存在就自动删掉
编写实体类User
@Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY)//主键 private int id; private String username; private String password; private String name; ... }
创建接口UserDao继承 JpaRepository
public interface UserDao extends JpaRepository<User,Integer>{ }
编写UserController
@RestController public class UserController { @Autowired private UserDao userDao; @RequestMapping("/user/list") public List<User> showUserList(){ return userDao.findAll(); //在UserDao所继承的JpaRepository中包含 findAll()方法 } }