3 ms·
Much more involved? With Java and co it’s literally the same. You add two dependencies to your gradle, write a dozen lines of code, and you’re done. Even if y
by kuschku 10y ago
Much more involved? With Java and co it’s literally the same.
You add two dependencies to your gradle, write a dozen lines of code, and you’re done.
Even if you go full enterprise it’s not much more. Let’s go full Java Enterprise:
// Enterprisify everything!
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.5.0.RELEASE'
compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '1.11.0.RELEASE'
compile group: 'org.springframework.data', name: 'spring-data-commons', version: '1.13.0.RELEASE'
// persistence framework
compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: '1.0.0.Final'
// database driver
compile group: 'org.postgresql', name: 'postgresql', version: '9.4.1212'
// to auto-generate getters, setters etc.
compileOnly "org.projectlombok:lombok:1.16.16"
Now we’ve imported spring, our database driver and an ORM. Let’s write the code.
First, let’s config:
// application config
spring.application.name=ourapp
server.port=8090
// database config
spring.datasource.url=<our database url>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driver-class-name=org.postgresql.Driver
Then add the database layer, defining our model:
@Entity @Table // To auto-generate mapping for the ORM
@Getter @Setter // To auto-generate getters and setters
public class Book {
@Id
private long id;
@Column
private String name;
@Column
private String description;
}
And our access layer:
public interface BookRepository extends CrudRepository<Book, Long> {
Optional<Book> findById(long id);
}
And our application:
@RestController
@SpringBootApplication
@EnableJpaRepositories
public class OurApplication {
@Autowired private BookRepository books;
@RequestMapping(path = "/{id}")
public Optional<Book> getBookById(@PathVariable long id) {
return books.findById(id);
}
public static void main(String[] args) {
SpringApplication.run(OurApplication.class, args);
}
}
So. This is if you go full insanely Java Enterprise, want full Spring, and everything. If you choose sanely, it’s obviously far less code.
Notice how I don’t have to use any transpilers, etc, and still get typing and the latest language features.