【发布时间】:2021-04-23 13:55:20
【问题描述】:
我在 mysql 中有表类别(cat_id、categoryName),我在 Spring 中使用 hibernate 检索它的记录。
但它只是检索 cat_id 而不是 categoryName
这是我的类别类映射到表
@Entity
@Table(name="categories")
public class Category {
@Id
@Column(name="cat_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name="categoryName")
private String categoryName;
public Category() {
}
public Category(String categoryName) {
super();
this.categoryName = categoryName;
}
@Override
public String toString() {
return "Category [id=" + id + ", categoryName=" + categoryName + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
}
这是我用来链接到前端的控制器类
public class mainController {
private CategoryService aCategoryService;
@Autowired
public mainController(CategoryService a2CategoryService)
{
aCategoryService= a2CategoryService;
}
@GetMapping("/")
public String homePage(Model theModel)
{
List<Category> theCategory= aCategoryService.findall();
System.out.println(theCategory);
theModel.addAttribute("categories",theCategory);
return "index2";
}
}
这是与存储库交互的类别服务实现
@Service
public class CategoryServiceImpl implements CategoryService {
private CategoryRepo categoryRepository;
@Autowired
public CategoryServiceImpl(CategoryRepo theCategoryRepo)
{
categoryRepository= theCategoryRepo;
}
@Override
public List<Category> findall() {
// TODO Auto-generated method stub
return categoryRepository.findAll();
}
@Override
public Category findById(int theId) {
// TODO Auto-generated method stub
Optional<Category> result = categoryRepository.findById(theId);
Category theCategory= null;
if (result.isPresent()) {
theCategory = result.get();
}
else {
// we didn't find the employee
throw new RuntimeException("Did not find category id - " + theId);
}
return theCategory;
}
@Override
public void save(Category theCategory) {
// TODO Auto-generated method stub
categoryRepository.save(theCategory);
}
@Override
public void deleteById(int theId) {
// TODO Auto-generated method stub
categoryRepository.deleteById(theId);
}
}
另外,我是 Java/Spring/Hibernate 的新手 我该怎么做才能解决这个问题
控制台日志 休眠:从类别category0_中选择category0_.cat_id作为cat_id1_0_,category0_.category_name作为category2_0_ [类别 [id=1, categoryName=null], 类别 [id=2, categoryName=null]]
【问题讨论】:
-
能否添加建表脚本?
-
你的意思是创建表的SQL脚本吗?
-
据我了解,您必须在@column 中添加列名。您在列名中使用了 _,但在类的属性中没有使用。
标签: java mysql spring hibernate spring-data-jpa