I am trying write web application with spring boot, but found the object returned from controller method become empty json, hers is my code:
Application.java
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableWebMvc
public class Application {
@Bean
public DataSource ds() {
BasicDataSource ds = new org.apache.commons.dbcp.BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/test");
ds.setUsername("root");
ds.setPassword("test");
return ds;
}
@Bean
public AbstractEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(ds());
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setPackagesToScan("hello");
return lef;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager();
}
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class);
CustomerRepository repository = context.getBean(CustomerRepository.class);
}
}
Customer.java
@Entity
@Table(name ="customer")
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
protected Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
MyController.java
@Controller
@RequestMapping("/customer")
public class MyController {
@Autowired
CustomerRepository customerRepository;
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody List<Customer> getAll() {
return (List<Customer>) customerRepository.findAll();
}
@RequestMapping(value="/{id}", method = RequestMethod.GET)
public @ResponseBody Customer findOne(@PathVariable long id) {
Customer customer = customerRepository.findOne(id);
System.out.println("--------------------------------");
System.out.println(customer);
return customer;
}
}
I can see the customer printed in the console, so I guess the data access is working, the only problem is why the customer object is converted to empty json.

Don't you need some public getters?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With