Sroing boot访问postgresql数据库

1. 配置pom.xml文件



	4.0.0

	com.example
	demo-1
	0.0.1-SNAPSHOT
	jar

	demo-1
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.6.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
		
  			postgresql
  			postgresql
  			9.1-901-1.jdbc4
		
		
  			org.postgresql
  			postgresql
  			runtime
		
		
  			org.springframework.boot
 			 spring-boot-starter-jdbc
		
		
  			org.springframework.boot
 			 spring-boot-starter-data-jpa
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	



2. application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=123456
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.hbm2ddl.auto=update
3. 实体类

package com.example.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User1 {
	
	@Id
	private Integer id;
	String name;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	

}

4. DAO

package com.example.respositroy;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.model.User1;

public interface UserRepository extends JpaRepository{

}

5 Controller

package com.example.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.Student;
import com.example.model.User1;
import com.example.respositroy.StudentRespositroy;
import com.example.respositroy.UserRepository;

@RestController
public class LoginController {

	@Autowired
	StudentRespositroy studentRepository;
	
	@Autowired
	UserRepository userRepository;
	
	@RequestMapping("/")
    public String home() {
        return "index";
    }
	
	@RequestMapping(value="/testdb")
	public List stuList(){
		return studentRepository.findAll();
	}
	
	@RequestMapping(value="/user")
	public List userList(){
		return userRepository.findAll();
	}
//    public String testDataBase(Map model){
//        //Long id = (long) 1;
//        Student stu = studentRepository.findStudentById(id);
//        model.put("student", stu);
//        return "testDataBase";
//    }
}

注:不要用数据库关键字定义表名或字段名(如 user)


你可能感兴趣的:(spring,boot,postgresql)