Home>

Already implemented except for the search function among the simple CRUD functions.
I want to add a search function (only search by name for the time being)
For the time being, it's simple, so I'd like to manage to implement the function.

problem.

When I enter a name in the search field of list.html, I want to be able to display only those that match that name in the list field.
I'm guessing that there is a problem with the description of the controller class or SearchRepositoryCustomImp.java, but is it going well in the first place?
There is no error code, so I don't know what caused it.

We would appreciate your help. Thank you.

It will be longer, but I will list the current source code.


[10/5 update]
Since there has been progress, we have updated the source code.
Update source code
-SearchRepositoryCustom.java
・ DemoController.java
・ SearchService.java

Up to SearchRepositoryCustom.java, it seems to work as expected.
However, although the list can be displayed if it is not entered, the list is not displayed when the search character is entered.
(If i press the search button without inputting, SELECT processing will be entered, but if you enter characters and press the button, SELECT processing will not be entered. Is it because SQL does not pass in the first place?)

Corresponding source code

AddressListApplication.java

package com.example.samplelist;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AddressListApplication {
    public static void main (String [] args) {
        SpringApplication.run (AddressListApplication.class, args);
    }
}

DemoController.java

package com.example.samplelist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import javax.annotation.PostConstruct;
@ComponentScan
@Controller
public class DemoController {
    private final UserRepository repos;
    @Autowired
    SearchService service;
    @Autowired
    public DemoController (UserRepository repos) {
        this.repos = repos;
    }
   /* Transition to list screen (initial screen) * /
    @GetMapping ("/")
    ModelAndView getAlllists (@RequestParam (required = false) String name, @RequestParam (required = false) String address,
            @RequestParam (required = false) String tel,
            @RequestParam (required = false) String zip,
            @RequestParam (required = false) String area) {
        ModelAndView mav = new ModelAndView ();
        User data = new User ();
        mav.addObject ("formModel", data);
        mav.addObject ("name", name);
        mav.addObject ("addrass", address);
        mav.addObject ("tel", tel);
        mav.addObject ("zip", zip);mav.addObject ("area", area);
        // COMMENT table: Get all records
       mav.addObject ("lists", repos.findAll ());
       mav.setViewName ("users/list");
        return mav;
    }
   /* Transition to new screen * /
    @GetMapping ("/ add")
    ModelAndView add () {
        ModelAndView mav = new ModelAndView ();
        User data = new User ();
        mav.addObject ("formModel", data);
        mav.setViewName ("users/new");
        return mav;
    }
   /* Transition to edit screen * /
    @GetMapping ("/ edit")
    ModelAndView edit (@RequestParam int id) {
        ModelAndView mav = new ModelAndView ();
        User data = repos.findById (id);
        mav.addObject ("formModel", data);
        mav.setViewName ("users/new");
        return mav;
    }
   /* Update process * /
    @PostMapping ("") // Fix here
    public String addComment (User user, BindingResult result, Model model) {
        model.addAttribute ("views", repos.findAll ());
        if (result.hasErrors ()) {
            return "users/list";
        }
        // COMMENT table: Comment registration
        repos.save (user);
        // Redirect to the root path ("/")
        return "redirect: /";
    }
   /* Delete process * /
    @DeleteMapping ("/ delete") // Modify here as well
    public String deleteComment (@Validated @ModelAttribute User user, BindingResult result, Model model) {
        model.addAttribute ("views", repos.findAll ());
        // COMMENT table: Delete record
        repos.deleteById (user.getId ());
        // Redirect to the root path ("/")
        return "redirect:/deletes";
    }
    @RequestMapping (value = "/ search", method = RequestMethod.GET)
    public String index () {
        return "users/list";
    }
    // Search function
     @RequestMapping (value = "/ search", method = RequestMethod.POST)
        public ModelAndView search (ModelAndView mav,
                @RequestParam (required = false) String name, @RequestParam (required = false) String address,
                @RequestParam (required = false) String tel,
                @RequestParam (required = false) String zip,
                @RequestParam (required = false) String area) {
            mav.setViewName ("users/list");
            mav.addObject ("name", name);
            List<User>lists = service.search (name, address, tel, zip, area);
            mav.addObject ("lists", lists);
            return mav;
     }
    @PostConstruct
    public void init () {
/ * Initial data creation part * /
    }
}

User.java

package com.example.samplelist;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table (name = "addresslist")
public class User {
    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    @Column
    private int id;
    @Column (name = "name")
    private String name;
    @Column
    private String address;
    @Column
    private String tel;
    @Column
    private String zip;
    @Column
    private String area;
     public int getId () {
            return id;
        }
        public void setId (int id) {
            this.id = id;
        }
        public String getName () {
            return name;
        }
        public void setName (String name) {
            this.name = name;
        }
        public String getAddress () {
            return address;
        }
        public void setAddress (String address) {
            this.address = address;
        }
        public String getTel () {
            return tel;
        }
        public void setTel (String tel) {
            this.tel = tel;
        }
        public String getZip () {
            return zip;
        }
        public void setZip (String zip) {
            this.zip = zip;
        }
        public String getArea () {
            return area;
        }
        public void setArea (String area) {
            this.area = area;
        }
}


UserRepository.java

package com.example.samplelist;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long>{
    public User findById (int id);
    public void deleteById (int id);
}


SearchService.java

package com.example.samplelist;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Servicepublic class SearchService {
    @Autowired
    UserRepository repos;
    SearchRepositoryCustom repositoryCustom;
    public List<User>search (String name, String address, String tel, String zip, String area) {
        List<User>lists;
        if ("". equals (name)) {
            lists = repos.findAll ();
        } else {
            lists = SearchRepositoryCustom.search (name, address, tel, zip, area);
        }
        return lists;
    }
}


SearchRepositoryCustom.java

package com.example.samplelist;
import java.io.Serializable;
import java.util.List;
// DAO class
public interface SearchRepositoryCustom extends Serializable {
    public static List<User>search (String name, String address, String tel, String zip, String area) {
        return null;
    }
}


SearchRepositoryCustomImp.java

package com.example.samplelist;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
@SuppressWarnings ("serial")
public class SearchRepositoryCustomImp implements SearchRepositoryCustom {
    @Autowired
    EntityManager manager;
    @SuppressWarnings ("unchecked")
    public List<User>search (String name, String address, String tel, String zip, String area) {
        StringBuilder sql = new StringBuilder ();
        sql.append ("SELECT g From User g WHERE");
        boolean andflg = false;
        boolean nameflg = false;
        boolean addressflg = false;
        boolean telflg = false;
        boolean zipflg = false;
        if (! "". Equals (name)&&name! = null) {
            if (andflg) sql.append ("AND");
            sql.append ("g.name LIKE%: name%");
            nameflg = true;
            andflg = true;
        }
        Query query = manager.createQuery (sql.toString ());
        if (nameflg) query.setParameter ("name", "%" + name + "%");

        return query.getResultList ();
    }
}

list.html

package com.example.samplelist;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long>{
    public User findById (int id);
    public void deleteById (int id);
}

`` ```

What I tried

I searched the search engine with the Spring search function etc. and referred to the hit sites as soon as possible.

Supplementary information (FW/tool version, etc.)

Please provide more detailed information here.

  • Answer # 1

    The description of the Controller argument is incorrect. @RequestParam is required, at least if you receive it as a request parameter.

    Also, if it is not a required parameter, use @RequestParam (required = false).

    import org.springframework.web.bind.annotation.RequestParam;
    @GetMapping ("/")
    ModelAndView getAlllists (@RequestParam (required = false) String name, @RequestParam (required = false) String address,
    @RequestParam (required = false) String tel,
    @RequestParam (required = false) String zip,
    @RequestParam (required = false) String area) {
    }

    If there are so many arguments, you can prepare another class (Form class), declare @ModelAttribute, and store it there.