Mình bị lỗi là khi edit nó ko tìm thấy id cũ mặc dù khi ấn edit thì id vẫn đổ lại mong ae và ad xem giúp vs

tran y

New Member
15/11/19
14
2
3
25
Java:
package com.learncode.Controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.learncode.Service.CategoryService;
import com.learncode.entity.Category;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;
  
    //lấy tất cả
    @RequestMapping("/")
    public String viewHomePage(Model model) {
        List<Category> listCategory = categoryService.findAll();
        model.addAttribute("listCategory", listCategory);
        return "category-view";
    }
    //thêm
    @RequestMapping("/new")
    public String showNewCategory(Model model) {
        Category category = new Category();
        model.addAttribute("category", category);
        return "category-register";
    }
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String saveCategory(@ModelAttribute("category")Category category) {
        categoryService.save(category);
        return "redirect:/category/";
    }
  
    @RequestMapping("/edit/{id}")
    public ModelAndView showEditCategory(@PathVariable(name = "id")Long id) {
        ModelAndView mav = new ModelAndView("category-edit");
        Category category  = categoryService.findById(id);
        mav.addObject("category", category); 
        return mav;
    }
    @RequestMapping("/delete/{id}")
    public String deleteCategory(@PathVariable(name = "id")Long id) {
        categoryService.deleteById(id);
        return "redirect:/category/";
    }
}
//////////////////////////////
package com.learncode.Service;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.learncode.Repository.CategoryRepository;
import com.learncode.entity.Category;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryRepository cateRepo;
    @PersistenceContext
    EntityManager entity;

    @Override
    public Category findById(Long id) {
        //this.entity.find(Category.class, id);
        return cateRepo.findById(id).get();
    }

    @Override
    public List<Category> findAll() {
        String hql = "FROM Category";
        TypedQuery<Category> query = entity.createQuery(hql, Category.class);
        List<Category> list = query.getResultList();
        return list;
    }

    @Override
    public Category save(Category category) {
        category.setId(ThreadLocalRandom.current().nextLong(0, new Long("900000000")));
        entity.persist(category);
        return category;
    }
    @Override
    public Category uploadt(Category category) {
        Category ce  = new Category();
        ce.setName(category.getName());
        this.entity.persist(ce);
        return category;
      
    }

    @Override
    public void deleteById(Long id) {
        this.cateRepo.deleteById(id);
    }
}
//////////////////////
package com.learncode.entity;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="qtht_category")
public class Category {
  
    @Id
    //@GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
  
    @OneToMany(mappedBy = "category")
    List<Products> products;

    public Category() {
        super();
    }

    public Category(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;
    }

    public List<Products> getProducts() {
        return products;
    }

    public void setProducts(List<Products> products) {
        this.products = products;
    }
  
}
[/CODE]
 
Last edited by a moderator:

quydtkt

Administrator
1/11/19
364
35
28
26
Bạn nên ghi rõ ra lỗi mình gặp phải. Hiện tại mình không hiểu bạn muốn hỏi gì
 

quydtkt

Administrator
1/11/19
364
35
28
26
Bạn gọi request nào khi submit form ở chế độ edit. Hiện tại chỉ có request category/edit/ để hiện thị trang edit. Nếu gọi request category/save khi submit trong trường hợp trong form không có id thì đương nhiên nó sẽ tạo thêm record khác.
 

tran y

New Member
15/11/19
14
2
3
25
Bạn gọi request nào khi submit form ở chế độ edit. Hiện tại chỉ có request category/edit/ để hiện thị trang edit. Nếu gọi request category/save khi submit trong trường hợp trong form không có id thì đương nhiên nó sẽ tạo thêm record khác.
rứa giờ mình phải làm sao ad
 

Joe

Thành viên VIP
21/1/13
2,935
1,304
113
@tran y
@quydtkt, @tranhuyvc , @macarong35
Mr. Tran Y, I don't know what browser you use (or via VPN) but I am tired of approving your reply or your posting every time when you start to post something new. If you don't check for the reasons why CDJ filter puts your ID into the potential spammer queue your question could get lost...

I am NOT an admin, nor a moderator so I cannot check for the reasons, and if the admins won't intervene your posting will get lost in the future. I do have some rights, but I am tired of doing the "approving" JOB of a mod.
 
Sửa lần cuối:

tran y

New Member
15/11/19
14
2
3
25
@tran y
@quydtkt, @tranhuyvc , @macarong35
Mr. Tran Y, I don't know what browser you use (or via VPN) but I am tired of approving your reply or your posting every time when you start to post something new. If you don't check for the reasons why CDJ filter puts your ID into the potential spammer queue your question could get lost...

I am NOT an admin, nor a moderator so I cannot check for the reasons, and if the admins won't intervene your posting will get lost in the future. I do have some rights, but I am tired of doing the "approving" JOB of a mod.
vâng tks ad để em mò mẩn khi có kết quả em sẽ thông báo


Edited by Joe:
Dear admins Quydtkt, Tranhuyvc and Macarong35 (or JackV)

Please check the account of Mr. Tran Y why he cannot post a question like a NORMAL member, but always needs an approvement of a moderator. I wonder why you, admins, let the forum be orphaned?
 
Last edited by a moderator:
  • Like
Reactions: Joe

tran y

New Member
15/11/19
14
2
3
25
vâng tks ad để em mò mẩn khi có kết quả em sẽ thông báo


Edited by Joe:
Dear admins Quydtkt, Tranhuyvc and Macarong35 (or JackV)

Please check the account of Mr. Tran Y why he cannot post a question like a NORMAL member, but always needs an approvement of a moderator. I wonder why you, admins, let the forum be orphaned?
I don't know if I should come up here and ask for help from the community
 

Joe

Thành viên VIP
21/1/13
2,935
1,304
113
I don't know if I should come up here and ask for help from the community
You could and should. I'm trying to contact the mentioned admins. Btw, your IP is DA NANG and then SAIGON. Are you using VPN or PROXY to access CongdongJava?
 

quydtkt

Administrator
1/11/19
364
35
28
26
Java:
    @Override
    public Category save(Category category) {
        category.setId(ThreadLocalRandom.current().nextLong(0, new Long("900000000")));
....
    }
Vấn đề của bạn nằm ở đây nhé.
Hibernate sẽ check entity trước khi lưu. Trường hợp tồn tại 1 record có cùng id với entity trong database thì sẽ update, ngược lại là insert. Bạn có thể chỉnh sửa theo hướng check nếu id null thì mới set id mới vào
 
  • Like
Reactions: tran y

tran y

New Member
15/11/19
14
2
3
25
Java:
    @Override
    public Category save(Category category) {
        category.setId(ThreadLocalRandom.current().nextLong(0, new Long("900000000")));
....
    }
Vấn đề của bạn nằm ở đây nhé.
Hibernate sẽ check entity trước khi lưu. Trường hợp tồn tại 1 record có cùng id với entity trong database thì sẽ update, ngược lại là insert. Bạn có thể chỉnh sửa theo hướng check nếu id null thì mới set id mới vào
tks để mình làm thử