mongodb を使用した spring-jpa のサンプル アプリケーションがあります。私は自分のサービスクラスを
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
//import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Component
public class Test {
@PersistenceContext
EntityManager em;
EntityManagerFactory emf;
@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
public String persist(Details details) {
Query query = em.createNativeQuery("db.Details.findOne(username= "+details.getUsername()+"& password= "+details.getPassword(), Details.class);
List<Details> resultList = query.getResultList();
System.out.println(query.toString());
Object t = null;
if (!em.contains(t)) {
em.persist(details);
em.flush();
System.out.println("Persist successful ...");
}
em.clear();
em.close();
return "persist";
}
}
コントローラ クラス
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
//import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloWorldController {
@Autowired
private Test test;
@RequestMapping("/")
public String hello() {
return "hello";
}
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String hi(@RequestParam("username") String username, @RequestParam("password") String password, ModelMap model) throws Exception{
Details details = new Details();
test.persist(details);
model.addAttribute("username", details.getUsername());
model.addAttribute("password", details.getPassword());
return "hi";
}
}
私のpojoクラスは
@Entity
@Table(name="Details")
public class Details {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "details")
@TableGenerator(name="details")
@Column
private int Id;
@Column
private String username;
@Column
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
私のアプリケーションは正常に動作しますが、データがデータベースに挿入されません。 QUERYについてはわかりません。データを取得できるようにクエリを変更する必要があることを教えてください。前もって感謝します。