IntelliJ IDEA+SpringBoot用JDBC做一个小型的javaWeb程序

一、首先,设计好数据库表,并且填上测试数据

二、新建一个Idea程序,使用Spring Initialzrxiangdao向导,选择web->web,SQL->jdbc,SQL->MySql,并且添加gson依赖库

三、配置启动文件Application.java

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

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

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return builder.sources(Application.class);
	}
}
四、在application.properties文件中配置数据连接信息
#DB Configuration:
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root

#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MYSQL5Dialect
五、建立bean文件夹,建立User.java实体类

public class User {
    public int id;
    public String name;
    public String passWord;
}
六、建立service/UserService.java文件

@Service
public class UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List getUserList() {
        String sql = "select * from user";
        RowMapper rowMapper = new RowMapper() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user=new User();
                user.id=resultSet.getInt("id");
                user.name=resultSet.getString("name");
                user.passWord=resultSet.getString("password");
                return user;
            }
        };
        return jdbcTemplate.query(sql, rowMapper);
    }
}
七、建立controller/UserController.java接口文件,编写接口方法,调用service方法,包装数据

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/getUser")
    public String getUser(){
        List userList = userService.getUserList();
        return new Gson().toJson(userList);
    }
}

八、运行程序

九、在浏览器或者PostMan工具中调用http://192.168.1.101:8080/getUser


返回结果:

[{"id":1,"name":"kalychen","passWord":"123456pwd"},{"id":2,"name":"will","passWord":"123456pwd"}]

和期望一样。

因为只是为APP做模拟数据,所以并没有打算深入研究,对我来说,能够读写数据库,能够购把数据打包,操作尽量简化,这就够了。






你可能感兴趣的:(Java,JavaWeb,Spring,Idea,IDE)