我正在尝试使用spring boot编写Web应用程序,但发现从控制器方法返回的对象变为空json,她的代码是我的代码:
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;
}
}
我可以看到客户在控制台中打印,所以我猜数据访问正常,唯一的问题是客户对象转换为空json的原因。
答案 0 :(得分:7)
你不需要一些公共吸气者吗?