Archive

Posts Tagged ‘Spring’

How to issue a JSON POST request to Spring Data Rest with a JPA relation

25 November 2014 Leave a comment

Lets say we have a class Company which has a relation to a class User

@Entity
@Table(name = "company")
public class Company implements java.io.Serializable {

	private static final long serialVersionUID = 1L;
	
	private Long id;
	private String name;
	private User user;

	public Company() {
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Column(name = "name", nullable = false, length = 200)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@ManyToOne(fetch = FetchType.LAZY, optional = false, targetEntity=my.example.User.class)
	@JoinColumn(name = "user_id")
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

and their corresponding repositories:

@RepositoryRestResource(collectionResourceRel = "company", path = "company")
public interface CompanyRepository extends JpaRepository<Company, Long>  {
}

@RepositoryRestResource(collectionResourceRel = "user", path = "user")
public interface UserRepository extends JpaRepository<User, Long> {

}

In order to add a user to the company (let’s say we want to link this company to the user with id of 2) you will need to issue the following JSON request to the company repository:

{
"name" : "a company name",
"user" : "http://localhost:8086/user/2"
}

The “user” variable should be the URL that is pointing to the user repository.

Advertisements
Categories: Java, Spring, Spring Data Rest Tags: ,

JEE presentation

1 December 2008 1 comment

Today I was invited to the City university to give a small talk about enterprise Java. It was my first ever talk in a university (it was quite different from giving presentation at work), and I was a bit nervous. Hope I did well because I really enjoyed it and I met interesting people. Thanks to everyone for coming.

If you would like to download the talk please follow the link: JEE

Categories: Java, Spring Tags: , ,