New unit test format

This commit is contained in:
Nick
2019-08-30 21:11:18 +01:00
parent db85c8f275
commit 6cd385e4c0
19972 changed files with 1626600 additions and 0 deletions
@@ -0,0 +1,14 @@
package com.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,70 @@
package com.baeldung.boot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.repository" })
@PropertySource("classpath:persistence-generic-entity.properties")
@EnableTransactionManagement
@Profile("default") //only required to allow H2JpaConfig and H2TestProfileJPAConfig to coexist in same project
//this demo project is showcasing several ways to achieve the same end, and class-level
//Profile annotations are only necessary because the different techniques are sharing a project
public class H2JpaConfig {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return hibernateProperties;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author paullatzelsperger
* @since 2019-03-20
*/
@Entity
public class Car {
@Id
@GeneratedValue
private int id;
private Integer power;
private String model;
public Car() {
}
public Car(int power, String model) {
this.power = power;
this.model = model;
}
public Integer getPower() {
return power;
}
public void setPower(Integer power) {
this.power = power;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getId() {
return id;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.boot.domain;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Country {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@Column(nullable = false)
private 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;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author harshavs
* @since 2019-08-01
*/
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue
private int id;
private String name;
private String title;
public Employee() {
}
public Employee(String name, String title) {
this.name = name;
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getId() {
return id;
}
}
@@ -0,0 +1,42 @@
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class GenericEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String value;
public GenericEntity() {
}
public GenericEntity(String value) {
this.value = value;
}
public GenericEntity(Long id, String value) {
this.id = id;
this.value = value;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,49 @@
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer status;
public User() {
}
public User(String name, Integer status) {
this.name = name;
this.status = status;
}
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;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.boot.naming;
import org.hibernate.jpa.boot.spi.IntegratorProvider;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import java.util.Collections;
import java.util.Map;
/**
* Custom implementation of the {@link HibernatePropertiesCustomizer HibernatePropertiesCustomizer}.
* We can use it to set custom hibernate properties.
*/
public class HibernateConfig implements HibernatePropertiesCustomizer {
@Override
public void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(MetadataExtractorIntegrator.INSTANCE));
}
}
@@ -0,0 +1,41 @@
package com.baeldung.boot.naming;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
/**
* Custom implementation of the {@link Integrator Integrator} interface.
* We can use it to getting access to the binding metadata between entity mappings and database tables.
*/
public class MetadataExtractorIntegrator implements Integrator {
public static final MetadataExtractorIntegrator INSTANCE = new MetadataExtractorIntegrator();
private Database database;
private Metadata metadata;
public Database getDatabase() {
return database;
}
public Metadata getMetadata() {
return metadata;
}
@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
this.database = metadata.getDatabase();
this.metadata = metadata;
}
@Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
}
}
@@ -0,0 +1,19 @@
package com.baeldung.boot.naming.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;
@Entity
public class Account {
@Id private Long id;
private String defaultEmail;
@OneToMany List<Preference> preferences;
@Column(name = "\"Secondary_Email\"") private String secondaryEmail;
}
@@ -0,0 +1,16 @@
package com.baeldung.boot.naming.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Preference {
@Id private Long id;
private String name;
@ManyToOne private Account account;
}
@@ -0,0 +1,26 @@
package com.baeldung.boot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.domain.Car;
/**
* @author paullatzelsperger
* @since 2019-03-20
*/
@Repository
public interface CarRepository extends JpaRepository<Car, Integer> {
boolean existsCarByPower(int power);
boolean existsCarByModel(String model);
@Query("select case when count(c)> 0 then true else false end from Car c where c.model = :model")
boolean existsCarExactCustomQuery(@Param("model") String model);
@Query("select case when count(c)> 0 then true else false end from Car c where lower(c.model) like lower(:model)")
boolean existsCarLikeCustomQuery(@Param("model") String model);
}
@@ -0,0 +1,15 @@
package com.baeldung.boot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.domain.Employee;
/**
* @author harshavs
* @since 2019-08-01
*/
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
}
@@ -0,0 +1,8 @@
package com.baeldung.boot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.boot.domain.GenericEntity;
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {
}
@@ -0,0 +1,83 @@
package com.baeldung.boot.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.domain.User;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
@Repository("userRepository")
public interface UserRepository extends JpaRepository<User, Integer> {
int countByStatus(int status);
Optional<User> findOneByName(String name);
Stream<User> findAllByName(String name);
@Async
CompletableFuture<User> findOneByStatus(Integer status);
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative();
@Query("SELECT u FROM User u WHERE u.status = ?1")
User findUserByStatus(Integer status);
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
User findUserByStatusNative(Integer status);
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
User findUserByStatusAndName(Integer status, String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
@Query("SELECT u FROM User u WHERE u.name like ?1%")
User findUserByNameLike(String name);
@Query("SELECT u FROM User u WHERE u.name like :name%")
User findUserByNameLikeNamedParam(@Param("name") String name);
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
User findUserByNameLikeNative(String name);
@Query(value = "SELECT u FROM User u")
List<User> findAllUsers(Sort sort);
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
@Modifying
@Query("update User u set u.status = :status where u.name = :name")
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@Modifying
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name);
}
@@ -0,0 +1,13 @@
package com.baeldung.disabledatasource.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.springbootcrudapp.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.baeldung.springbootcrudapp.application"})
@EnableJpaRepositories(basePackages="com.baeldung.springbootcrudapp.application.repositories")
@EnableTransactionManagement
@EntityScan(basePackages="com.baeldung.springbootcrudapp.application.entities")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,66 @@
package com.baeldung.springbootcrudapp.application.controllers;
import com.baeldung.springbootcrudapp.application.repositories.UserRepository;
import com.baeldung.springbootcrudapp.application.entities.User;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class UserController {
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/signup")
public String showSignUpForm(User user) {
return "add-user";
}
@PostMapping("/adduser")
public String addUser(@Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-user";
}
userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
@GetMapping("/edit/{id}")
public String showUpdateForm(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
model.addAttribute("user", user);
return "update-user";
}
@PostMapping("/update/{id}")
public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
user.setId(id);
return "update-user";
}
userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
userRepository.delete(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
}
@@ -0,0 +1,56 @@
package com.baeldung.springbootcrudapp.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
@NotBlank(message = "Email is mandatory")
private String email;
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
}
@@ -0,0 +1,13 @@
package com.baeldung.springbootcrudapp.application.repositories;
import com.baeldung.springbootcrudapp.application.entities.User;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByName(String name);
}
@@ -0,0 +1,27 @@
package com.baeldung.springbootdatasourceconfig.application;
import com.baeldung.springbootdatasourceconfig.application.entities.User;
import com.baeldung.springbootdatasourceconfig.application.repositories.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner run(UserRepository userRepository) throws Exception {
return (String[] args) -> {
User user1 = new User("John", "john@domain.com");
User user2 = new User("Julie", "julie@domain.com");
userRepository.save(user1);
userRepository.save(user2);
userRepository.findAll().forEach(user -> System.out.println(user.getName()));
};
}
}
@@ -0,0 +1,20 @@
package com.baeldung.springbootdatasourceconfig.application.datasources;
import javax.sql.DataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DataSourceBean {
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
dataSourceBuilder.username("SA");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
}
@@ -0,0 +1,46 @@
package com.baeldung.springbootdatasourceconfig.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
public User(){}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
}
@@ -0,0 +1,8 @@
package com.baeldung.springbootdatasourceconfig.application.repositories;
import com.baeldung.springbootdatasourceconfig.application.entities.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {}
@@ -0,0 +1,14 @@
package com.baeldung.springboothibernate.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.springboothibernate.application.datasources;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceBean {
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
dataSourceBuilder.username("SA");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
}
@@ -0,0 +1,40 @@
package com.baeldung.springboothibernate.application.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String name;
public Book() {
super();
}
public Book(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.springboothibernate.application.repositories;
import com.baeldung.springboothibernate.application.models.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}
@@ -0,0 +1,19 @@
package com.baeldung.springboothibernate.application.services;
import com.baeldung.springboothibernate.application.models.Book;
import com.baeldung.springboothibernate.application.repositories.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> list() {
return bookRepository.findAll();
}
}
@@ -0,0 +1,12 @@
package com.baeldung.springboothsqldb.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.springboothsqldb.application.controllers;
import com.baeldung.springboothsqldb.application.entities.Customer;
import com.baeldung.springboothsqldb.application.repositories.CustomerRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
private final CustomerRepository customerRepository;
@Autowired
public CustomerController(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@PostMapping("/customers")
public Customer addCustomer(@RequestBody Customer customer) {
customerRepository.save(customer);
return customer;
}
@GetMapping("/customers")
public List<Customer> getCustomers() {
return (List<Customer>) customerRepository.findAll();
}
}
@@ -0,0 +1,55 @@
package com.baeldung.springboothsqldb.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
public Customer() {}
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
}
@@ -0,0 +1,8 @@
package com.baeldung.springboothsqldb.application.repositories;
import com.baeldung.springboothsqldb.application.entities.Customer;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {}
@@ -0,0 +1,22 @@
package com.baeldung.tomcatconnectionpool.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.baeldung.tomcatconnectionpool.application"})
@EnableJpaRepositories(basePackages="com.baeldung.tomcatconnectionpool.application.repositories")
@EnableTransactionManagement
@EntityScan(basePackages="com.baeldung.tomcatconnectionpool.application.entities")
public class SpringBootConsoleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootConsoleApplication.class);
}
}
@@ -0,0 +1,53 @@
package com.baeldung.tomcatconnectionpool.application.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public long getId() {
return id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
@Override
public String toString() {
return "Customer{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + '}';
}
}
@@ -0,0 +1,12 @@
package com.baeldung.tomcatconnectionpool.application.repositories;
import com.baeldung.tomcatconnectionpool.application.entities.Customer;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
@@ -0,0 +1,37 @@
package com.baeldung.tomcatconnectionpool.application.runners;
import com.baeldung.tomcatconnectionpool.application.entities.Customer;
import com.baeldung.tomcatconnectionpool.application.repositories.CustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CommandLineCrudRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(CommandLineCrudRunner.class);
@Autowired
private CustomerRepository customerRepository;
@Override
public void run(String... args) throws Exception {
customerRepository.save(new Customer("John", "Doe"));
customerRepository.save(new Customer("Jennifer", "Wilson"));
logger.info("Customers found with findAll():");
customerRepository.findAll().forEach(c -> logger.info(c.toString()));
logger.info("Customer found with findById(1L):");
Customer customer = customerRepository.findById(1L)
.orElseGet(() -> new Customer("Non-existing customer", ""));
logger.info(customer.toString());
logger.info("Customer found with findByLastName('Wilson'):");
customerRepository.findByLastName("Wilson").forEach(c -> {
logger.info(c.toString());
});
}
}
@@ -0,0 +1,11 @@
spring.datasource.driver-class-name = org.hsqldb.jdbc.JDBCDriver
spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.username = sa
spring.datasource.password =
spring.jpa.hibernate.ddl-auto = create
# Enabling H2 Console
spring.h2.console.enabled=true
# Uppercase Table Names
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
File diff suppressed because one or more lines are too long
@@ -0,0 +1,10 @@
insert into users values (1, 'Alex', 1);
insert into users values (2, 'Bob', 1);
insert into users values (3, 'John', 0);
insert into users values (4, 'Harry', 0);
insert into users values (5, 'Smith', 1);
INSERT INTO country (name) VALUES ('India');
INSERT INTO country (name) VALUES ('Brazil');
INSERT INTO country (name) VALUES ('USA');
INSERT INTO country (name) VALUES ('Italy');
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,8 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
jdbc.pass=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
@@ -0,0 +1,15 @@
drop table if exists USERS;
drop table if exists country;
create table USERS(
ID int not null AUTO_INCREMENT,
NAME varchar(100) not null,
STATUS int,
PRIMARY KEY ( ID )
);
CREATE TABLE country (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(128) NOT NULL,
PRIMARY KEY (id)
);
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Add User</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
<link rel="stylesheet" href="../css/shards.min.css">
</head>
<body>
<div class="container my-5">
<h2 class="mb-5">New User</h2>
<div class="row">
<div class="col-md-6">
<form action="#" th:action="@{/adduser}" th:object="${user}" method="post">
<div class="row">
<div class="form-group col-md-6">
<label for="name" class="col-form-label">Name</label>
<input type="text" th:field="*{name}" class="form-control" id="name" placeholder="Name">
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label for="email" class="col-form-label">Email</label>
<input type="text" th:field="*{email}" class="form-control" id="email" placeholder="Email">
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="col-md-6 mt-5">
<input type="submit" class="btn btn-primary" value="Add User">
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Users</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
<link rel="stylesheet" href="../css/shards.min.css">
</head>
<body>
<div th:switch="${users}" class="container my-5">
<div class="row">
<div class="col-md-6">
<h2 th:case="null">No users yet!</h2>
<div th:case="*">
<h2 class="my-5">Users</h2>
<table class="table table-striped table-responsive-md">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
<td><a th:href="@{/edit/{id}(id=${user.id})}" class="btn btn-primary"><i class="fas fa-user-edit ml-2"></i></a></td>
<td><a th:href="@{/delete/{id}(id=${user.id})}" class="btn btn-primary"><i class="fas fa-user-times ml-2"></i></a></td>
</tr>
</tbody>
</table>
</div>
<p class="my-5"><a href="/signup" class="btn btn-primary"><i class="fas fa-user-plus ml-2"></i></a></p>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Update User</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
<link rel="stylesheet" href="../css/shards.min.css">
</head>
<body>
<div class="container my-5">
<h2 class="mb-5">Update User</h2>
<div class="row">
<div class="col-md-6">
<form action="#" th:action="@{/update/{id}(id=${user.id})}" th:object="${user}" method="post">
<div class="row">
<div class="form-group col-md-6">
<label for="name" class="col-form-label">Name</label>
<input type="text" th:field="*{name}" class="form-control" id="name" placeholder="Name">
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label for="email" class="col-form-label">Email</label>
<input type="text" th:field="*{email}" class="form-control" id="email" placeholder="Email">
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="col-md-6 mt-5">
<input type="submit" class="btn btn-primary" value="Update User">
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,33 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.config.H2JpaConfig;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, H2JpaConfig.class })
public class SpringBootH2IntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
@@ -0,0 +1,29 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
@@ -0,0 +1,31 @@
package com.baeldung;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
import com.baeldung.config.H2TestProfileJPAConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class })
@ActiveProfiles("test")
public class SpringBootProfileIntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
@@ -0,0 +1,62 @@
package com.baeldung.boot.naming;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Account;
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
"spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl"
})
@Import(Config.class)
public class LegacyJpaImplNamingIntegrationTest extends NamingConfig {
@Test
public void givenLegacyJpaImplNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
String entity = Account.class.getCanonicalName();
PersistentClass persistentClass = metadata.getEntityBinding(entity);
Table table = persistentClass.getTable();
String physicalNameExpected = "Secondary_Email";
String implicitNameExpected = "defaultEmail";
String tableNameExpected = "Account";
String tableNameCreated = table.getName();
boolean columnNameIsQuoted = table
.getColumn(3)
.isQuoted();
String physicalNameCreated = table
.getColumn(3)
.getName();
String implicitNameCreated = table
.getColumn(2)
.getName();
SoftAssertions.assertSoftly(softly -> {
softly
.assertThat(columnNameIsQuoted)
.isTrue();
softly
.assertThat(tableNameCreated)
.isEqualTo(tableNameExpected);
softly
.assertThat(physicalNameCreated)
.isEqualTo(physicalNameExpected);
softly
.assertThat(implicitNameCreated)
.isEqualTo(implicitNameExpected);
});
}
}
@@ -0,0 +1,15 @@
package com.baeldung.boot.naming;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
public class NamingConfig {
@TestConfiguration
static class Config {
@Bean
public HibernatePropertiesCustomizer customizer() {
return new HibernateConfig();
}
}
}
@@ -0,0 +1,56 @@
package com.baeldung.boot.naming;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Account;
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy",
"spring.jpa.hibernate.naming.implicit-strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
})
@Import(Config.class)
public class SpringBootDefaultNamingIntegrationTest extends NamingConfig {
@Test
public void givenDefaultBootNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
String entity = Account.class.getCanonicalName();
PersistentClass persistentClass = metadata.getEntityBinding(entity);
Table table = persistentClass.getTable();
String physicalNameExpected = "secondary_email";
String implicitNameExpected = "default_email";
String tableNameExpected = "account";
String tableNameCreated = table.getName();
String physicalNameCreated = table
.getColumn(3)
.getName();
String implicitNameCreated = table
.getColumn(2)
.getName();
SoftAssertions softly = new SoftAssertions();
softly
.assertThat(tableNameCreated)
.isEqualTo(tableNameExpected);
softly
.assertThat(physicalNameCreated)
.isEqualTo(physicalNameExpected);
softly
.assertThat(implicitNameCreated)
.isEqualTo(implicitNameExpected);
softly.assertAll();
}
}
@@ -0,0 +1,63 @@
package com.baeldung.boot.naming;
import com.baeldung.boot.naming.MetadataExtractorIntegrator;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Preference;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collection;
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
"spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl",
})
@Import(Config.class)
public class StrategyLegacyHbmImplIntegrationTest extends NamingConfig {
@Test
public void givenLegacyHbmImplNamingNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
String entity = Preference.class.getCanonicalName();
PersistentClass persistentClass = metadata.getEntityBinding(entity);
Collection<Table> tables = metadata
.getDatabase()
.getDefaultNamespace()
.getTables();
Table preferenceTable = persistentClass.getTable();
String tableNameExpected = "Account_preferences";
Table accountPreferencesTable = tables
.stream()
.filter(table -> table
.getName()
.equals(tableNameExpected))
.findFirst()
.get();
String implicitNameExpected = "account";
String implicitNameCreated = preferenceTable
.getColumn(3)
.getName();
String tableNameCreated = accountPreferencesTable.getName();
SoftAssertions.assertSoftly(softly -> {
softly
.assertThat(implicitNameCreated)
.isEqualTo(implicitNameExpected);
softly
.assertThat(tableNameCreated)
.isEqualTo(tableNameExpected);
});
}
}
@@ -0,0 +1,34 @@
package com.baeldung.boot.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.domain.User;
import com.baeldung.boot.repository.UserRepository;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by adam.
*/
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("multiplesqlfiles")
public class UserRepositoryMultipleSqlFilesIntTest {
@Autowired private UserRepository userRepository;
@Test
public void givenTwoImportFilesWhenFindAllShouldReturnSixUsers() {
Collection<User> users = userRepository.findAll();
assertThat(users.size()).isEqualTo(6);
}
}
@@ -0,0 +1,68 @@
package com.baeldung.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableJpaRepositories(basePackages = { "com.baeldung.repository", "com.baeldung.boot.repository" })
@EnableTransactionManagement
@Profile("test") //only required to allow H2JpaConfig and H2TestProfileJPAConfig to coexist in same project
//this demo project is showcasing several ways to achieve the same end, and class-level
//Profile annotations are only necessary because the different techniques are sharing a project
public class H2TestProfileJPAConfig {
@Autowired
private Environment env;
@Bean
@Profile("test")
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return hibernateProperties;
}
}
@@ -0,0 +1,81 @@
package com.baeldung.springbootcrudapp.application.tests;
import com.baeldung.springbootcrudapp.application.controllers.UserController;
import com.baeldung.springbootcrudapp.application.entities.User;
import com.baeldung.springbootcrudapp.application.repositories.UserRepository;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
public class UserControllerUnitTest {
private static UserController userController;
private static UserRepository mockedUserRepository;
private static BindingResult mockedBindingResult;
private static Model mockedModel;
@BeforeClass
public static void setUpUserControllerInstance() {
mockedUserRepository = mock(UserRepository.class);
mockedBindingResult = mock(BindingResult.class);
mockedModel = mock(Model.class);
userController = new UserController(mockedUserRepository);
}
@Test
public void whenCalledshowSignUpForm_thenCorrect() {
User user = new User("John", "john@domain.com");
assertThat(userController.showSignUpForm(user)).isEqualTo("add-user");
}
@Test
public void whenCalledaddUserAndValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(false);
assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("index");
}
@Test
public void whenCalledaddUserAndInValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(true);
assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("add-user");
}
@Test(expected = IllegalArgumentException.class)
public void whenCalledshowUpdateForm_thenIllegalArgumentException() {
assertThat(userController.showUpdateForm(0, mockedModel)).isEqualTo("update-user");
}
@Test
public void whenCalledupdateUserAndValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(false);
assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("index");
}
@Test
public void whenCalledupdateUserAndInValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(true);
assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("update-user");
}
@Test(expected = IllegalArgumentException.class)
public void whenCalleddeleteUser_thenIllegalArgumentException() {
assertThat(userController.deleteUser(1l, mockedModel)).isEqualTo("index");
}
}
@@ -0,0 +1,46 @@
package com.baeldung.springbootcrudapp.application.tests;
import com.baeldung.springbootcrudapp.application.entities.User;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class UserUnitTest {
@Test
public void whenCalledGetName_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
assertThat(user.getName()).isEqualTo("Julie");
}
@Test
public void whenCalledGetEmail_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
assertThat(user.getEmail()).isEqualTo("julie@domain.com");
}
@Test
public void whenCalledSetName_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
user.setName("John");
assertThat(user.getName()).isEqualTo("John");
}
@Test
public void whenCalledSetEmail_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
user.setEmail("john@domain.com");
assertThat(user.getEmail()).isEqualTo("john@domain.com");
}
@Test
public void whenCalledtoString_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
assertThat(user.toString()).isEqualTo("User{id=0, name=Julie, email=julie@domain.com}");
}
}
@@ -0,0 +1,31 @@
package com.baeldung.springbootdatasourceconfig.application.tests;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.springbootdatasourceconfig.application.entities.User;
import com.baeldung.springbootdatasourceconfig.application.repositories.UserRepository;
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryIntegrationTest {
@Autowired
private UserRepository userRepository;
@Test
public void whenCalledSave_thenCorrectNumberOfUsers() {
userRepository.save(new User("Bob", "bob@domain.com"));
List<User> users = (List<User>) userRepository.findAll();
// 2 additional users are saved in the CommandLineRunner bean
assertThat(users.size()).isEqualTo(3);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.springboothibernate.application.tests;
import com.baeldung.springboothibernate.application.models.Book;
import com.baeldung.springboothibernate.application.services.BookService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BookServiceUnitTest {
@Autowired
private BookService bookService;
@Test
public void whenApplicationStarts_thenHibernateCreatesInitialRecords() {
List<Book> books = bookService.list();
Assert.assertEquals(books.size(), 3);
}
}
@@ -0,0 +1,61 @@
package com.baeldung.springboothsqldb.application.tests;
import com.baeldung.springboothsqldb.application.entities.Customer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomerControllerUnitTest {
private static MediaType MEDIA_TYPE_JSON;
@Autowired
private MockMvc mockMvc;
@Before
public void setUpJsonMediaType() {
MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
}
@Test
public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception {
Customer customer = new Customer("John", "john@domain.com");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter();
String requestJson = objectWriter.writeValueAsString(customer);
this.mockMvc
.perform(MockMvcRequestBuilders.post("/customers")
.contentType(MEDIA_TYPE_JSON)
.content(requestJson)
)
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/customers"))
.andExpect(MockMvcResultMatchers.content().contentType(MEDIA_TYPE_JSON))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
@@ -0,0 +1,37 @@
package com.baeldung.springbootinitialload.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.repository.EmployeeRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Sql({"/employees_schema.sql", "/import_employees.sql"})
public class SpringBootInitialLoadIntegrationTest {
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void testLoadDataForTestClass() {
assertEquals(3, employeeRepository.findAll()
.size());
}
@Test
@Sql(scripts = {"/import_senior_employees.sql"}, config = @SqlConfig(encoding = "utf-8", transactionMode = TransactionMode.ISOLATED))
public void testLoadDataForTestCase() {
assertEquals(5, employeeRepository.findAll()
.size());
}
}
@@ -0,0 +1,31 @@
package com.baeldung.springbootinitialload.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
import org.springframework.test.context.jdbc.SqlGroup;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.repository.EmployeeRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@SqlGroup({ @Sql(scripts = "/employees_schema.sql", config = @SqlConfig(transactionMode = TransactionMode.ISOLATED)),
@Sql("/import_employees.sql")})
public class SpringBootSqlGroupAnnotationIntegrationTest {
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void testLoadDataForTestCase() {
assertEquals(3, employeeRepository.findAll().size());
}
}
@@ -0,0 +1,25 @@
package com.baeldung.tomcatconnectionpool.test.application;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.tomcatconnectionpool.application.SpringBootConsoleApplication;
import static org.assertj.core.api.Assertions.*;
import org.springframework.boot.test.context.SpringBootTest;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringBootConsoleApplication.class})
public class SpringBootTomcatConnectionPoolIntegrationTest {
@Autowired
private DataSource dataSource;
@Test
public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() {
assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource");
}
}
@@ -0,0 +1 @@
spring.jpa.properties.hibernate.hbm2ddl.import_files=import_active_users.sql,import_inactive_users.sql
@@ -0,0 +1,16 @@
# spring.datasource.x
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql, import_books.sql
spring.datasource.data=import_*_users.sql
@@ -0,0 +1,8 @@
drop table EMPLOYEES if exists;
create table EMPLOYEES(
ID int not null AUTO_INCREMENT,
NAME varchar(100) not null,
TITLE varchar(100),
PRIMARY KEY ( ID )
);
@@ -0,0 +1,3 @@
insert into USERS(name, status, id) values('Peter', 1, 1);
insert into USERS(name, status, id) values('David', 1, 2);
insert into USERS(name, status, id) values('Ed', 1, 3);
@@ -0,0 +1,3 @@
insert into book values(1, 'The Tartar Steppe');
insert into book values(2, 'Poem Strip');
insert into book values(3, 'Restless Nights: Selected Stories of Dino Buzzati');
@@ -0,0 +1,3 @@
insert into EMPLOYEES values(1, 'Harsha', 'Developer');
insert into EMPLOYEES values(2, 'John', 'Tester');
insert into EMPLOYEES values(3, 'Ram', 'Manager');
@@ -0,0 +1,3 @@
insert into users(name, status, id) values('Monica', 0, 4);
insert into users(name, status, id) values('Paul', 0, 5);
insert into users(name, status, id) values('George', 0, 6);
@@ -0,0 +1,2 @@
insert into EMPLOYEES values(4, 'Eric', 'Senior Developer');
insert into EMPLOYEES values(5, 'Vidhyaah', 'Senior Manager');
@@ -0,0 +1,3 @@
insert into USERS(name, status, id) values('Peter', 1, 7);
insert into USERS(name, status, id) values('David', 1, 8);
insert into USERS(name, status, id) values('Ed', 1, 9);