Spring Boot JPA MySQL

Spring JPA

Spring JPA is JPA based data access for Spring.
This is family of Spring Data.

Prepare MySQL

MySQL create database and table

create database crm;

Crate table

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

I inserted one data for test named ‘Taro’

application.yml

Settings for database is applicaiton.yml(src/main/resources/application.yml)

spring:
  datasource:
    url: jdbc:mysql://localhost/crm
    username: username
    password: password
    driverClassName: com.mysql.jdbc.Driver 

Prepare Repository

We need to prepare entity and repository for database operations.

Entity

Entity is model class
I use lombok for getter and setter.
If you want to know more about lombok please read other my blog entry(Spring Boot lombok)

@Data
@Entity
public class User {

	@Id
	@GeneratedValue
	private Integer id;
	
	@Column
	private String name;
	
	public User() {
		
	}
}

Repository

Repository is operation class

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

	List<User> findByName(String name);
}

findByName is addtional. This is from column name(name).

Test Controller

This is operation testing

@RestController
@RequestMapping(value="/jpa/users")
public class JPAUserController {

	@Autowired
	UserRepository userRepository;
	
	
	@RequestMapping(value="/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<User> findAllUser() {
		List<User> list = userRepository.findAll();
		return list;
	}
	
	@RequestMapping(value="create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public User createUser(@RequestBody ValidUser validUser) {
		User user = new User();
		user.setName(validUser.getName());
		user = userRepository.save(user);
		return user;
	}
	
	// count
	@RequestMapping(value="count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public long count(@RequestBody ValidUser validUser) {
		return userRepository.count();
	}
	
	// where(id)
	@RequestMapping(value="getone", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public User getUser(@RequestParam Integer id) {
		User user = userRepository.findOne(id);
		return user;
	}
	
	// where(id)
	@RequestMapping(value="find", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<User> getUser(@RequestParam String name) {
		return userRepository.findByName(name);
	}
}

Testing

GET: http://localhost:8080/jpa/users/list
POST http://localhost:8080/jpa/users/create Body : {“name”: “Jiro”} Content-Type: application/json;
GET: http://localhost:8080/jpa/users/count
GET: http://localhost:8080/jpa/users/getone?id=1
GET: http://localhost:8080/jpa/users/find?name=Taro