gpt4 book ai didi

spring-mvc - 非空对象变为空json

转载 作者:行者123 更新时间:2023-12-05 08:58:21 28 4
gpt4 key购买 nike

我正在尝试使用 spring boot 编写 web 应用程序,但发现从 Controller 方法返回的对象变为空 json,她的是我的代码:

应用程序.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。

enter image description here

最佳答案

你不需要一些公共(public) setter/getter 吗?

关于spring-mvc - 非空对象变为空json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050804/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com