Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Удаление записи и вывод названи полей, Rest веб сервис, появились проблемы 
:(
    Опции темы
neosky
Дата 7.4.2015, 08:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 1
Регистрация: 30.5.2014

Репутация: нет
Всего: нет



Всем привет, создаю веб сервис (использую: Java, Maven, TomCat, MySql, Hibernate). Появилась необходимость удалять записи из таблицы базы, а также вывести GET запросом название полей таблицы. Сделал как смог но код получился не рабочий, возвращает 204 (No Content), и ничего не меняется.


hibernate.cfg.xml:

Код

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 
    
    <session-factory>
        
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testws</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        
        
        
      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
      
      
      <property name="show_sql">true</property>
      
      <mapping class="com.mycompany.testws.model.Person"/>
    </session-factory>
        
</hibernate-configuration>


Person.java:

Код

package com.mycompany.testws.model;
 
import static com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type.Int;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
 
/**
 *
 * @author F
 */
 
@Entity
@Table(name="PERSON")
@XmlRootElement(name="person")
@XmlType(propOrder={"id", "fullName", "age"})
//@RestPageableQueries
public class Person {
 
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ID")
    private int id;
    @Column(name="FULL_NAME")
    private String fullName;
    @Column(name="AGE")
    private int age;
@XmlElement
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
@XmlElement
    public String getFullName() {
        return fullName;
    }
 
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
@XmlElement
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
    
    
}


PersonDao.java:

Код

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.testws.dao;

import com.mycompany.testws.model.Person;
import com.mycompany.testws.util.HibernateUtil;
import static com.mycompany.testws.util.HibernateUtil.getSessionFactory;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jgroups.tests.perf.Test;

/**
 *
 * @author F
 */
public class PersonDao {

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public Person getPersonById(int id) {
        Person person = null;
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            person = (Person) session.createQuery("from Person p where p.id = :ID").setParameter("ID", id).uniqueResult();
            session.getTransaction().commit();
        } catch (Exception ex) {
            if (session != null) {
                session.getTransaction().rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return person;
    }

    public List<Person> getPaging(int Page, int Size) {
        List<Person> persons = null;
        Session session = null;
        int pageSize = Size;
        int pageNumber = Page;

        session = sessionFactory.openSession();
        session.beginTransaction();
        String countQ = "Select count (p.id) from Person p";

        Query countQuery = session.createQuery(countQ);

        Long countResults = (Long) countQuery.uniqueResult();
        Query selectQuery = session.createQuery("from Person p");
        selectQuery.setFirstResult((pageNumber - 1) * pageSize);
        selectQuery.setMaxResults(pageSize);

        return selectQuery.list();

    }

//return selectQuery.list();
//session.getTransaction().commit();
    //    persons;
    public List<Person> getAllPersons() {
        List<Person> persons = null;
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            persons = session.createQuery("from Person p").list();
            session.getTransaction().commit();
        } catch (Exception ex) {
            if (session != null) {
                session.getTransaction().rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return persons;
    }

    public List<Person> getAsc() {
        List<Person> persons = null;
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            persons = session.createQuery("from Person p order by age ASC").list();
            session.getTransaction().commit();
        } catch (Exception ex) {
            if (session != null) {
                session.getTransaction().rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return persons;
    }

    public List<Person> getDesc() {
        List<Person> persons = null;
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            persons = session.createQuery("from Person p order by id DESC").list();
            session.getTransaction().commit();
        } catch (Exception ex) {
            if (session != null) {
                session.getTransaction().rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return persons;
    }
    
       public List<Person> getHeaders() {
        List<Person> persons = null;
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            persons = session.createQuery("select * from COLUMNS WHERE table_name='person'").list();
            session.getTransaction().commit();
        } catch (Exception ex) {
            if (session != null) {
                session.getTransaction().rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return persons;
    }

    public boolean savePerson(Person person) {
        Session session = null;
        boolean hasErrors = false;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            session.saveOrUpdate(person);
            session.getTransaction().commit();

        } catch (Exception ex) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            hasErrors = true;

        } finally {
            if (session != null) {
                session.close();
            }
        }
        return hasErrors;
    }

    public String deleteById(int id) {
        Person person = null;
        Session session = null;

        String hql = "delete from Person where id = :ID";
        Query query = session.createQuery(hql);
        query.setParameter("ID", id);
        int rowCount = query.executeUpdate();

        return "sssss";

//            
//            session = sessionFactory.openSession();
//            session.beginTransaction();
//            person = (Person) session.createQuery("delete from Person where id = :ID").setParameter("ID", id).uniqueResult();
//            session.getTransaction().commit();
    }
}




Service.java
Код

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.testws.services;

import com.mycompany.testws.dao.PersonDao;
import com.mycompany.testws.model.Person;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import static javax.ws.rs.HttpMethod.POST;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 *
 * @author F
 */
@Path("service")
public class Service {
//    
//    //simulate db 
//    private static Map<Integer, Person> persons = new HashMap<Integer, Person>();
//    
//    //insert test data in db
//    
//    static {
//    for (int i = 0;i<10;i++){
//    Person person = new Person();
//    int id = i+1;
//    person.setId(id);
//    person.setFullName("My wonderful Person " + id);
//    person.setAge(new Random().nextInt(40) + 1);
//    
//    persons.put(id, person);
//    
//    }
//    }

    private PersonDao personDao = new PersonDao();

    //method which return a single person in xml
    @GET
    @Path("/getPersonByIdXML/{id}")
    @Produces(MediaType.APPLICATION_XML)
    public Person getPersonByIdXML(@PathParam("id") int id) {
        return personDao.getPersonById(id);
    }

    //return in JSON
    @GET
    @Path("/getPersonByIdJSON/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Person getPersonById(@PathParam("id") int id) {
        return personDao.getPersonById(id);
    }

    //method return list all person
    @GET
    @Path("/getAllJSON")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getAllPersonsInJSONroo() {
        return personDao.getAllPersons();
    }
    
       @GET
    @Path("sort/ageAsc")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getSortAgeAsc() {
        return personDao.getAsc();
    }
    
       @GET
    @Path("sort/idDesc")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getSortIdDesc() {
        return personDao.getDesc();
    }
    
     @GET
    @Path("/getHeaders")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getHeaders() {
        return personDao.getHeaders();
    }

    //insert
    @GET
    @Path("/insertPerson/{fullName}/{age}")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveNewPerson(@PathParam("fullName") String fullName, @PathParam("age") int age) {
        Person person = new Person();

        person.setFullName(fullName);
        person.setAge(age);

        if (!personDao.savePerson(person)) {
            return "{\"status\":\"ok\"}  id=" + person.getId();
        } else {
            return "{\"status\":\"not ok\"}";
        }

    }
    //update

    @GET
    @Path("/insertPerson/{id}/{fullName}/{age}")
    @Produces(MediaType.APPLICATION_JSON)
    public String updatePerson(@PathParam("id") int id, @PathParam("fullName") String fullName, @PathParam("age") int age) {
        Person person = new Person();
        person.setId(id);
        person.setFullName(fullName);
        person.setAge(age);

        if (!personDao.savePerson(person)) {
            return "{\"status\":\"ok\"}";
        } else {
            return "{\"status\":\"not ok\"}";
        }

    }

    @DELETE
    @Path("/del/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteById(@PathParam("id") int id) {
        return "delee";

    }

    @GET
    @Path("/getPage/{page}/{size}")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> deleteById(@PathParam("page") int page, @PathParam("size") int size) {
        // return personDao.getAbsentDetails(page, size) + "\"%n\"";
        return personDao.getPaging(page, size);
    }

}


PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java EE (J2EE) и Spring | Следующая тема »


 




[ Время генерации скрипта: 0.0423 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.